Running bash script from within python

前端 未结 7 905
死守一世寂寞
死守一世寂寞 2020-11-27 11:50

I have a problem with the following code:

callBash.py:

import subprocess
print \"start\"
subprocess.call(\"sleep.sh\")
print \"end\"         


        
7条回答
  •  日久生厌
    2020-11-27 11:58

    If sleep.sh has the shebang #!/bin/sh and it has appropriate file permissions -- run chmod u+rx sleep.sh to make sure and it is in $PATH then your code should work as is:

    import subprocess
    
    rc = subprocess.call("sleep.sh")
    

    If the script is not in the PATH then specify the full path to it e.g., if it is in the current working directory:

    from subprocess import call
    
    rc = call("./sleep.sh")
    

    If the script has no shebang then you need to specify shell=True:

    rc = call("./sleep.sh", shell=True)
    

    If the script has no executable permissions and you can't change it e.g., by running os.chmod('sleep.sh', 0o755) then you could read the script as a text file and pass the string to subprocess module instead:

    with open('sleep.sh', 'rb') as file:
        script = file.read()
    rc = call(script, shell=True)
    

提交回复
热议问题