无法在python中按名称获取进程的PID

无法在python中按名称获取进程的PID,python,subprocess,Python,Subprocess,我有一段非常简单的代码 import subprocess print(subprocess.check_output(["pidof","ffmpeg"])) 它应该打印名为ffmpeg的进程的PID(请参阅)。但是,我总是遇到以下错误: subprocess.CalledProcessError: Command '['pidof', 'ffmpeg']' returned non-zero exit status 1 用于蟒蛇2和蟒蛇3。我做错了什么?来自manpidof: EXIT

我有一段非常简单的代码

import subprocess
print(subprocess.check_output(["pidof","ffmpeg"]))
它应该打印名为
ffmpeg
的进程的PID(请参阅)。但是,我总是遇到以下错误:

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

用于蟒蛇2和蟒蛇3。我做错了什么?

来自
manpidof

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

       1      No program was found with the requested name.

您只是没有任何名为
ffmpeg

的进程,您可以使用try-except来避免阻塞执行

用这个

import subprocess

try:

    print(subprocess.check_output(["pidof","ffmpeg"]))
except subprocess.CalledProcessError:
    print("no process named ffmpeg")
出现错误是因为if
pidof ffmpeg
不提供输出并使用
print(subprocess.check_output([“pidof”,“ffmpeg”]))
我们期待该命令的输出

你也可以使用

print(subprocess.getoutput(“pidof ffmpeg”))

即使该命令的输出为
none

如果您检查库方法
检查输出
,您可以找到

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.... """

这是因为当前没有进程按名称“ffmpeg”激活,但是当我在bash上运行相同的命令时,没有收到错误消息。但如果进程以非零代码退出,则通过检查输出退出1可引发被调用的进程错误: