Python:子进程并运行带有多个参数的bash脚本

问题描述 投票:24回答:5

如何使用子进程模块运行bash脚本,我必须给出几个参数?

这就是我目前使用的:

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

bash脚本似乎没有采用任何参数。任何见解都非常感谢!

python bash arguments subprocess popen
5个回答
33
投票

将参数作为列表传递,请参阅the very first code example in the docs

import subprocess

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

如果arg3不是字符串;在传递给check_call()之前将其转换为字符串:arg3 = str(arg3)


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

如果使用shell = True,脚本及其参数必须作为字符串传递。 args序列中的任何其他元素都将被视为shell的参数。

您可以在http://docs.python.org/2/library/subprocess.html#subprocess.Popen找到完整的文档。


2
投票

嗨,我知道这是解决方案已经很晚了,但可以帮助别人。

例:

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

subprocess.check_call(pass_arg)

上面的示例提供了arg1和arg2作为shell脚本test.sh的参数

从本质上讲,子进程需要一个数组。因此,您可以填充数组并将其作为参数提供。


0
投票

还有一个例子,它不包含在上述所有例子中,

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

请注意,当您键入%(argument1,argument2,argument3)时,%(之间不应有任何空格,例如% (argument1,argument2,argument3)无效。


-1
投票

你忘了添加args名字。

subprocess.Popen(args=['./test.sh', 'arg1 arg2 %s' % arg3], shell=True)
© www.soinside.com 2019 - 2024. All rights reserved.