Running bash script from within python
--
Track title: CC O Beethoven - Piano Sonata No 3 in C
--
Chapters
00:00 Question
00:34 Accepted answer (Score 120)
01:17 Answer 2 (Score 71)
02:23 Answer 3 (Score 45)
02:50 Answer 4 (Score 37)
03:18 Thank you
--
Full question
https://stackoverflow.com/questions/1374...
Answer 3 links:
[source]: http://docs.python.org/2/library/subproc...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #bash #call
#avk47
ACCEPTED ANSWER
Score 124
Making sleep.sh 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 "sleep.sh" to "./sleep.sh".)
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.
ANSWER 2
Score 77
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)
ANSWER 3
Score 37
Actually, you just have to add the shell=True argument:
subprocess.call("sleep.sh", shell=True)
But beware -
Warning Invoking the system shell with shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.
ANSWER 4
Score 16
Make sure that sleep.sh has execution permissions, and run it with shell=True:
#!/usr/bin/python
import subprocess
print "start"
subprocess.call("./sleep.sh", shell=True)
print "end"