【问题标题】:Python: Multiple arguments being passed as a single argument?Python:多个参数作为单个参数传递?
【发布时间】:2021-09-21 20:55:41
【问题描述】:

我正在使用 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)

【问题讨论】:

  • 这就是将字符串传递给call 方法的想法。
  • help(subprocess.call) 在 python 交互式 shell 中会向您展示如何正确地做到这一点。
  • 谢谢,我去看看

标签: python python-3.x string command-line arguments


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您帮助我添加了shell=True
  • 不要将列表参数和shell=True 结合使用。传递列表的全部意义在于避免需要一个shell。如果你需要一个 shell,你最好构建一个合适的字符串,而不是让subprocess 尝试从你的列表中构建一个。
猜你喜欢
  • 1970-01-01
  • 2011-03-29
  • 1970-01-01
  • 2015-04-11
  • 2021-08-24
  • 2016-07-21
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
相关资源
最近更新 更多