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

use*_*173 26 python bash arguments subprocess popen

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

这就是我目前使用的:

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

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

jfs*_*jfs 39

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

import subprocess

subprocess.check_call(['/my/file/path/programname.sh', 'arg1', 'arg2', arg3])
Run Code Online (Sandbox Code Playgroud)

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

  • 不幸的是,代码中的示例没有回答原始问题,因为他们选择了只有一个参数的过于简单的情况.目前还不清楚是应该将多个参数作为单个字符串传递,还是作为多个参数传递,除非您在页面中阅读了POpen背后的详细信息.即便如此,它只会说,"提供一系列参数通常是首选的" - 不是,"你必须提供多个参数作为列表" (6认同)

小智 6

subprocess.Popen(['/my/file/path/programname.sh arg1 arg2 %s' % arg3], shell = True).
Run Code Online (Sandbox Code Playgroud)

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

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