无法在python

时间:2019-04-26 09:03:04

标签: python subprocess

我有一段非常简单的代码

import subprocess
print(subprocess.check_output(["pidof","ffmpeg"]))

应该打印名为ffmpeg的进程的PID(请参阅here)。但是,我总是收到以下错误:

subprocess.CalledProcessError: Command '['pidof', 'ffmpeg']' returned non-zero exit status 1

适用于python2和python3。我在做什么错了?

2 个答案:

答案 0 :(得分:1)

来自man pidof

EXIT STATUS
       0      At least one program was found with the requested name.

       1      No program was found with the requested name.

您只是没有名为ffmpeg的进程。

答案 1 :(得分:1)

您可以使用try来避免执行被阻塞

使用此

import subprocess

try:

    print(subprocess.check_output(["pidof","ffmpeg"]))
except subprocess.CalledProcessError:
    print("no process named ffmpeg")

由于pidof ffmpeg没有给出任何输出并使用 print(subprocess.check_output(["pidof","ffmpeg"]))我们期望该命令输出。

您也可以使用

print(subprocess.getoutput("pidof ffmpeg"))

即使该命令的输出为none

,也不会出错

如果您检查库方法check_output,则可以找到

def check_output(*popenargs, timeout=None, **kwargs):
    r"""Run command with arguments and return its output.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

    The arguments are the same as for the Popen constructor.... """