[英]Python execute shell command with variables inside (quoted) command string
我正在编写一个 python 脚本来使用映射文件(基于 json)通过 sed 替换 txt 文件中的字符串:
import json
import sys
import subprocess
file_to_edit = str(sys.argv[1])
a_dictionary = {"a.b.c.d": "e.f.g.h"}
for pair in a_dictionary.items():
orig = pair[0] //"a.b.c.d"
repl = pair[1] //"e.f.g.h"
现在我想执行以下 shellcommand(在脚本中): sed -i 's/orig/repl/g' filetoedit
。
或者我会手动输入什么sed -i 's/abcd/efgh/g' datafile.txt
所以引号让我很恼火,因为我找不到如何将我的变量值插入到 shellcommand 的命令字符串中的方法所需的格式被破坏。 另一个问题是,从我所见,它也取决于您如何执行 shellcommand,所以如果我希望我的脚本等到 sed 完成,我不知道哪个是正确的。
有谁知道我怎么能做到这一点?
谢谢
如果您通过 shell 执行命令,则只需要引号。 当您使用subprocess()
,您可以通过将命令作为列表而不是字符串传递来直接执行命令。
subprocess.run(["sed", "-i", f"s/{orig}/{repl}/g", file_to_edit]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.