【问题标题】:why is subprocess.popen returning an empty string为什么 subprocess.popen 返回一个空字符串
【发布时间】:2013-05-14 15:07:04
【问题描述】:

我正在使用 python 的 subprocess.popen 来获取视频文件的信息。

output = Popen('ffmpeg -i "'+avifile+'" -dframes 0 -vframes 0', 
    executable="/bin/bash", stdout=PIPE, stderr=STDOUT,
    shell=True).communicate()[0]

问题是每当我运行它时,当我知道应该有某些东西时,输出变量都是一个空字符串。我可以手动运行ffmpeg。

我在想这可能是管道和重定向的问题。想知道是否有人可以解决这个问题。

【问题讨论】:

  • output = Popen(...).communicate() 给你什么?也许你得到一个错误
  • 没有错误,什么都没有。
  • 传递参数序列而不是字符串,您将避免引号问题

标签: python subprocess popen


【解决方案1】:

将组合的 stdout/stderr 读取为字符串并获取非零返回状态的异常:

from subprocess import STDOUT, check_output as qx

output = qx(['ffmpeg', '-i', avifile] + '-dframes 0 -vframes 0'.split(),
            stderr=STDOUT)

除非你需要,否则不要使用shell=True

【讨论】:

  • ...为什么qx?我认为这是一个令人困惑的名称,我认为没有理由用它来更改可读的 check_output
  • 可读性取决于您的背景。 qx (eXecute) 的起源是 bash 中的反引号(向后引号)`command` 和 perl 中对应的 qx(command) 运算符。
【解决方案2】:
cmd = ['ffmpeg','-i',avifile,'-dframes','0','-vframes', '0']

output = Popen(cmd, 
    #executable="/bin/bash", ive never seen this used ... you may not need it
    stdout=PIPE, stderr=PIPE,
    shell=True).communicate()

试试吧……

【讨论】:

  • 我得到 TypeError: execv() arg 2 必须只包含字符串。 avifile 是一个字符串变量。
  • 什么是avifile? print avifile,type(avifile)
  • 这是没有引号的 0。但它仍然没有工作。输出变量为空。
  • 该命令是否实际输出任何内容?如果你在shell中运行它有输出?
  • 你能把shell的命令和输出复制粘贴到你原来的问题中吗? ...我要睡觉了...但这将有助于其他人回答您的问题
【解决方案3】:

我将变量 output 更改为 video_output 并且由于某种原因它起作用了。我完全不知道为什么。

【讨论】:

  • 我的 猜测 是您以某种方式覆盖了 output 变量,因此现在重命名它,代码不再覆盖它。如果您发布了 MWE,那么我们就不会浪费时间进行推测,但我们可以指出真正的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 2013-10-22
  • 2021-10-09
相关资源
最近更新 更多