[英]Unable to get PID of a process by name in python
我有一段非常簡單的代碼
import subprocess
print(subprocess.check_output(["pidof","ffmpeg"]))
它將打印名為ffmpeg
的進程的PID(請參閱此處 )。 但是,我總是收到以下錯誤:
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.... """
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.