Python 带引号的查询子流程

Python subprocess for queries with quotes

我需要触发这个在终端上完美运行的查询:

sed -i '' '/default\]/a\'$'\n''  Hello world'$'\n' <PATH_TO_FILE>

这会在我找到 "default]" 字符串的下方添加一行。

使用 python 代码:

query = r""" sed -i '' '/default\]/a\'$'\n''  Hello world'$'\n' %s """ % (PATH_T)_FILE)
proc = subprocess.Popen(query.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err =  proc.communicate()

但是,命令在 python 中失败,错误为:

Error executing the query  sed -i '' '/default\]/a\'$'\n''  Hello world'$'\n' /Users/hshah/tmpFile . output = , error = sed: 1: "'/default\]/a\'$'\n''": invalid command code '

这可能是什么问题?

split 每个 空格上。这导致 query.split() 成为

['sed',
 '-i',
 "''",
 "'/default\]/a\'$'\n''",
 'Hello',
 "world'$'\n'",
 '/tmp/foo']

这不是你想要的。手动构建 subprocess.Popen 的参数,而不是拆分字符串。