Python: subprocess and running a bash script with

2019-02-02 23:26发布

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!

5条回答
走好不送
2楼-- · 2019-02-02 23:29

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).

查看更多
贪生不怕死
3楼-- · 2019-02-02 23:30

Hi I know that this is solution is quite late, but could help someone.

example:

import subprocess
pass_arg=[]
pass_arg[0]="/home/test.sh"
pass_arg[1]="arg1"
pass_arg[2]="arg2"

subprocess.check_call(pass_arg)

The above example provides arg1 and arg2 as parameters to the shell script test.sh

Essentially, subprocess expects an array. So you could populate an array and provide it as a parameter.

查看更多
beautiful°
4楼-- · 2019-02-02 23:37
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.

查看更多
太酷不给撩
5楼-- · 2019-02-02 23:38

You forgot to add args name.

subprocess.Popen(args=['./test.sh', 'arg1 arg2 %s' % arg3], shell=True)
查看更多
Evening l夕情丶
6楼-- · 2019-02-02 23:53

One more example, which is not included in all the above ones,

subprocess.Popen(['/your/script.sh %s %s %s' %(argument1,argument2,argument3)], shell = True)

Please note that, when you type %(argument1,argument2,argument3), there should not be any space between % and (, eg % (argument1,argument2,argument3) is not valid.

查看更多
登录 后发表回答