Embed bash in python

后端 未结 9 1311
别那么骄傲
别那么骄傲 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 13:55

    Is

    import os
    os.system ("bash -c 'echo $0'")
    

    going to do it for you?

    EDIT: regarding readability

    Yes, of course, you can have it more readable

    import os
    script = """
    echo $0
    ls -l
    echo done
    """
    os.system("bash -c '%s'" % script)
    

    EDIT2: regarding macros, no python does not go so far as far as i know, but between

    import os
    def sh(script):
        os.system("bash -c '%s'" % script)
    
    sh("echo $0")
    sh("ls -l")
    sh("echo done")
    

    and previous example, you basically get what you want (but you have to allow for a bit of dialectical limitations)

提交回复
热议问题