首页 > 解决方案 > 字符串中的多个变量

问题描述

我想从 Python 运行一些 bash 命令。我已经能够做到这一点subprocess.Popen。在某些情况下,我想为命令添加一些参数,例如“stdin”或“cwd”。问题是我想自动化一些东西,所以我想把命令和它的参数放在一个文件中。

我正在使用这样的结构:

this is a command that I want to execute, stdin=example
this is another command
I execute a third command, cwd=folder/

在我的 python 脚本中,我逐行阅读,并执行以下操作:

line = line.split(",", 1)
cmd = subprocess.Popen(line[0].split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE)

我想再添加一个可以使其他参数通用的参数。我知道像

cmd = subprocess.Popen(line[0].split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd="folder/")

有效,但我想放一些类似的东西

cmd = subprocess.Popen(line[0].split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE, line[1].split(",")) (maybe I should put another delimiter for the args)

但这不起作用。

我不知道如何表达这一点,也不知道它使用的是什么具体概念,所以如果答案在这个意义上是完整的,我将非常感激。

标签: pythonsubprocess

解决方案


执行时line = line.split(",", 1),它会创建一个包含 2 个元素的列表。

对于第一个条目,它是["this is a command that I want to execute", " stdin=example"]

但请注意,在第二个元素(“stdin=example”)中,第一个字符是一个空格。发生这种情况是因为line.split()调用时仅使用逗号作为分隔符,而不是逗号空格。

解决方案是将 更改","", ".

不确定这是否是导致您的问题的原因...


推荐阅读