Python: subprocess and running a bash script with multiple arguments


Question

How do I go about running a bash script using the subprocess module, to which I must give several arguments?

This is what I'm currently using:

subprocess.Popen(['/my/file/path/programname.sh', 'arg1 arg2 %s' % arg3], \
    shell = True)

The bash script seems not to be taking any of the parameters in. Any insights are greatly appreciated!

1
24
6/21/2013 7:40:42 PM

Accepted Answer

Pass arguments as a list, see the very first code example in the docs:

import subprocess

subprocess.check_call(['/my/file/path/programname.sh', 'arg1', 'arg2', arg3])

If arg3 is not a string; convert it to string before passing to check_call(): arg3 = str(arg3).

36
6/21/2013 7:57:48 PM

subprocess.Popen(['/my/file/path/programname.sh arg1 arg2 %s' % arg3], shell = True).

If you use shell = True the script and its arguments have to be passed as a string. Any other elements in the args sequence will be treated as arguments to the shell.

You can find the complete docs at http://docs.python.org/2/library/subprocess.html#subprocess.Popen.


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