Python:子进程并运行带有多个参数的 bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17242828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: subprocess and running a bash script with multiple arguments
提问by user2510173
How do I go about running a bash script using the subprocess module, to which I must give several arguments?
如何使用 subprocess 模块运行 bash 脚本,我必须为其提供几个参数?
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!
bash 脚本似乎没有采用任何参数。非常感谢任何见解!
采纳答案by jfs
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 arg3is not a string; convert it to string before passing to check_call(): arg3 = str(arg3).
如果arg3不是字符串;在传递给check_call():之前将其转换为字符串arg3 = str(arg3)。
回答by loentar
You forgot to add argsname.
你忘记加args名字了。
subprocess.Popen(args=['./test.sh', 'arg1 arg2 %s' % arg3], shell=True)
回答by loentar
subprocess.Popen(['/my/file/path/programname.sh arg1 arg2 %s' % arg3], shell = True).
If you use shell = Truethe script and its arguments have to be passed as a string. Any other elements in the argssequence will be treated as arguments to the shell.
如果您使用shell = True脚本,则必须将其参数作为字符串传递。args序列中的任何其他元素都将被视为 shell 的参数。
You can find the complete docs at http://docs.python.org/2/library/subprocess.html#subprocess.Popen.
您可以在http://docs.python.org/2/library/subprocess.html#subprocess.Popen找到完整的文档。
回答by Sairaj Madhavan
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
上面的例子提供了 arg1 和 arg2 作为 shell 脚本 test.sh 的参数
Essentially, subprocess expects an array. So you could populate an array and provide it as a parameter.
本质上,子进程需要一个数组。因此,您可以填充一个数组并将其作为参数提供。
回答by Chintan Gotecha
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)
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.
请注意,当你输入%(argument1,argument2,argument3),不应该有之间的任何空间%和(,如% (argument1,argument2,argument3)无效。

