首页 > 解决方案 > Python:多个参数作为单个参数传递?

问题描述

我正在使用 subprocess 来使用命令行并为另一个脚本传递参数。我有一个参数列表,我把它做成了一个字符串:

import subprocess as sp

arg_list = ["arg1", "arg2", "arg3"]
arg_string = " ".join(arg_list)

现在这适用于以下输出arg1 arg2 arg3。问题是,当我将它传递给命令行时,它只将其识别为一个参数。

sp.call(["test_file.tcl", arg_string])

** 注意:我call只使用这个脚本需要 Python 3.4

我知道这只是一个论点,因为将以下内容添加到 .tcl 文件中:

[lindex $argv 0]
[lindex $argv 1]
[lindex $argv 2]

输出是:

arg1 arg2 arg3
. (These are blank lines not dots)
.

这是正确的方法吗?我怎样才能使这项工作真正在 3 个参数而不是 1 个参数中被识别?

** 答:添加shell=True允许传递字符串而不是列表。

sp.call("test_file.tcl {0}".format(arg_string), shell=True)

标签: pythonpython-3.xstringcommand-linearguments

解决方案


不要加入args_list字符串,然后使用 splat 运算符。这将传递['test_file.tcl', 'arg1', 'arg2', 'arg3']call.

sp.call(["test_file.tcl", *arg_list])

根据您的操作系统,您可能还需要通过shell=True


推荐阅读