Python - 子进程 cmd 作为列表未正确扩展



有什么想法为什么我作为命令传递给subprocess((的这个列表没有正确扩展吗?

file_name = "some_make_file"
cmd = ['gmake', '-pn', '-f', file_name, '|', 'grep', '-A1', '"^# makefile"', '|', 'grep', '-v', '"^#|^--"', '|', 'sort', '|', 'uniq']
proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = prod.communicate()

输出是一个 gmake 错误,如果我自己加入 cmd 以在 cmd 行上测试它,我会得到这个:

#join
" ".join(cmd)
#output
('gmake -pn -f some_make_file | grep -A1 "^ makefile" | grep -v '
'"^#\|^--" | sort | uniq')

对于我的生活,我似乎无法弄清楚这个命令有什么问题。有什么想法吗?难道我没有好好逃脱吗?添加一个特殊的字符却没有意识到?

您没有运行中间 shell,因此无法将 | 解释为管道命令。即使你设置了 shell=True,因为你传入了一个列表,它也会被转义。正确的管道方式在官方 python 文档中给出 替换 Shell Pipeline – tdelaney

最新更新