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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python:子进程并运行带有多个参数的bash脚本相关的知识,希望对你有一定的参考价值。

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

这就是我目前使用的:

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

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

答案

将参数作为列表传递,请参阅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)

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

另一答案

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

例:

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.Popen(['/your/script.sh %s %s %s' %(argument1,argument2,argument3)], shell = True)

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

另一答案

你忘了添加args名字。

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

以上是关于Python:子进程并运行带有多个参数的bash脚本的主要内容,如果未能解决你的问题,请参考以下文章

Python线程化多个bash子进程?

Python 子进程 - 通过 SSH 运行多个 shell 命令

使用子进程运行多个 bash 命令

使用 asyncio 将 bash 作为 Python 的子进程运行,但 bash 提示被延迟

Bash命令在终端中有效,但在python脚本中的“子进程”中无效[重复]

使用子进程从 Python 运行 PDAL bash 命令的问题 [重复]