【问题标题】:Python - subprocess cmd as list not expanding properlyPython - 子进程 cmd 作为列表未正确扩展
【发布时间】:2017-05-09 22:47:20
【问题描述】:

任何想法为什么我作为命令传递给 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 显示什么错误?
  • 命令按显示运行,这就是为什么我尝试加入列表以测试实际传递给 subprocess.Popen() 的内容。问题是该列表以某种方式破坏了命令。输出是一条 gmake 错误消息。
  • 不,问题是您将管道字符作为参数传递给 gmake,而不是创建 shell 管道。要么使用shell=True,要么(最好)使用pipes。甚至用 bash 或 zsh 代替 Python 编写你的 shell 脚本。
  • 您没有运行中间 shell,因此没有什么可以将 | 解释为管道命令。即使你设置了shell=True,因为你传入了一个列表,它也会被转义。官方python文档Replacing Shell Pipeline中给出了正确的管道方式
  • 试试`shlex`,阅读这个答案stackoverflow.com/a/43808675/7414759

标签: python python-3.x


【解决方案1】:

您没有运行中间 shell,因此没有什么可以解释 |作为管道命令。即使你设置了shell=True,因为你传入了一个列表,它也会被转义。官方 python 文档Replacing Shell Pipeline - tdelaney 中给出了正确的管道方式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 2018-03-25
    相关资源
    最近更新 更多