python - 字符串中的多个变量
问题描述
我想从 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)
但这不起作用。
我不知道如何表达这一点,也不知道它使用的是什么具体概念,所以如果答案在这个意义上是完整的,我将非常感激。
解决方案
执行时line = line.split(",", 1)
,它会创建一个包含 2 个元素的列表。
对于第一个条目,它是["this is a command that I want to execute", " stdin=example"]
但请注意,在第二个元素(“stdin=example”)中,第一个字符是一个空格。发生这种情况是因为line.split()
调用时仅使用逗号作为分隔符,而不是逗号和空格。
解决方案是将 更改","
为", "
.
不确定这是否是导致您的问题的原因...
推荐阅读
- python - 无法在文本字段中输入文本
- javascript - 使用 url-parse 解析 url
- android - 无法实施 firebase-ui-auth
- linux - 安装 Apache Spot
- r - 如何合并没有公共列的两个数据框
- excel - 从多个关闭的工作簿中提取特定单元格
- selenium - pageLoadTimeout 在 Selenium 中不起作用 - Java
- python - 在 VSCode 终端上运行 Python 文件导致 ModuleNotFoundError
- groovy - NiFi:为 ExecuteScript 处理器编写代码以组合多个条目
- node.js - 在中间件的本地初始化列表对象,但它不起作用