繁体   English   中英

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

[英]Python: subprocess and running a bash script with multiple arguments

如何使用 subprocess 模块运行 bash 脚本,我必须给它几个参数?

这是我目前正在使用的:

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

bash 脚本似乎没有包含任何参数。非常感谢任何见解!

将参数作为列表传递,请参阅文档中的第一个代码示例

import subprocess

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

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

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找到完整的文档。

再举一个例子,上面所有的例子都没有,

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

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

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

例子:

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

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

您忘记添加args名称。

subprocess.Popen(args=['./test.sh', 'arg1 arg2 %s' % arg3], shell=True)

这就是它对我有用的方式

import subprocess
subprocess.Popen(["path/to/file.sh", arg1, arg2, arg3])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM