Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run shell script from python

Tags:

python

I am trying to run a shell script from a python script using the following:

from subprocess import call
call(['bash run.sh'])

This gives me an error, but I can successfully run other commands like:

call(['ls'])
like image 439
The Nightman Avatar asked Aug 18 '15 23:08

The Nightman


3 Answers

You should separate arguments:

call(['bash', 'run.sh'])
call(['ls','-l'])
like image 127
Assem Avatar answered Oct 26 '22 23:10

Assem


from subprocess import call
import shlex
call(shlex.split('bash run.sh'))

You want to properly tokenize your command arguments. shlex.split() will do that for you.

Source: https://docs.python.org/2/library/subprocess.html#popen-constructor

Note shlex.split() can be useful when determining the correct tokenization for args, especially in complex cases:

like image 24
Joe Young Avatar answered Oct 26 '22 22:10

Joe Young


When you call call() with a list, it expects every element of that list to correspond to a command line argument. In this case it is looking for bash run.sh as the executable with spaces and everything as a single string.

Try one of these:

call("bash run.sh".split())
call(["bash", "run.sh"])
like image 44
ntki Avatar answered Oct 26 '22 22:10

ntki