Embed bash in python

后端 未结 9 1221
别那么骄傲
别那么骄傲 2020-12-25 13:43

I am writting a Python script and I am running out of time. I need to do some things that I know pretty well in bash, so I just wonder how can I embed some bash lines into a

相关标签:
9条回答
  • 2020-12-25 14:07

    There is also the commands module to give more control over the output: https://docs.python.org/2/library/commands.html

    0 讨论(0)
  • 2020-12-25 14:09

    I created Sultan to address exactly what you're trying to do. It doesn't have any external dependencies, and tries to be as light as possible and provides a Pythonic interface to Bash.

    https://github.com/aeroxis/sultan

    0 讨论(0)
  • 2020-12-25 14:13

    subprocess and os.system() works fine when bash commands are simple and does not have brackets, commas and quotes. Simple way to embed complex bash argument is to add bash script at the end of python script with a unique string comments and use simple os.system() commands to tail and convert to bash file.

    #!/usr/bin/python
    ## name this file  "file.py"
    import os
    def get_xred(xx,yy,zz):
        xred=[]
    ####gaur###
        xred.append([     zz[9] ,  zz[19] ,  zz[29]     ])
        xred.append([     zz[9] ,  xx[9]  ,  yy[9]      ])
        xred.append([     zz[10],  zz[20] ,  zz[30]     ])
        xred.append([     zz[10],  xx[10] ,  yy[10]     ])
    ###nitai###
        xred=np.array(xred)
        return xred
    ## following 3 lines executes last 6 lines of this file.
    os.system("tail -n 6 file.py >tmpfile1")
    os.system("sed 's/###123//g' tmpfile1>tmpfile2")
    os.system("bash tmpfile2")
    ###### Here ###123 is a unique string to be removed
    ###123#!/bin/sh
    ###123awk '/###gaur/{flag=1;next}/###nitai/{flag=0} flag{print}' file.py >tmp1
    ###123cat tmp1 | awk '{gsub("xred.append\\(\\[","");gsub("\\]\\)","");print}' >tmp2
    ###123awk 'NF >0' tmp2 > tmp3
    ###123sed '$d' tmp3 |sed '$d' | sed '$d' >rotation ; rm tmp*
    
    0 讨论(0)
提交回复
热议问题