Running bash script from within python


I have a problem with the following code:

import subprocess
print "start""")
print "end"

sleep 10

I want the "end" to be printed after 10s. (I know that this is a dumb example, I could simply sleep within python, but this simple file was just as a test)

12/6/2012 2:25:16 PM

Accepted Answer

Making executable and adding shell=True to the parameter list (as suggested in previous answers) works ok. Depending on the search path, you may also need to add ./ or some other appropriate path. (Ie, change "" to "./".)

The shell=True parameter is not needed (under a Posix system like Linux) if the first line of the bash script is a path to a shell; for example, #!/bin/bash.

12/6/2012 2:42:00 PM

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

import subprocess

rc ="")

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("./")

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

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow