我有一段非常简单的代码
import subprocess
print(subprocess.check_output(["pidof","ffmpeg"]))
应该打印名为ffmpeg
的进程的PID(参见here)。但是,我总是收到以下错误:
subprocess.CalledProcessError: Command '['pidof', 'ffmpeg']' returned non-zero exit status 1
对于python2和python3。我究竟做错了什么?
来自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
的进程。
你可以使用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.... """