我有这个代码获取特定进程的pid;代码运行良好,但有时我得到这个错误:
psutil.NoSuchProcess: Process no longer exists (pid=xxxx)
如何解决这个问题?如果发生此错误或其他错误,我该如何重新启动脚本?
import psutil
my_pid = None
pids = psutil.pids()
for pid in pids:
ps = psutil.Process(pid)
# find process by .exe name, but note that there might be more instances of solitaire.exe
if "solitaire.exe" in ps.name():
my_pid = ps.pid
print( "%s running with pid: %d" % (ps.name(), ps.pid) )
问题是,在发现给定程序的pid(进程ID)和循环到达它试图检查它的点之间,该进程已经停止运行。
您可以使用try
/except
:
for pid in pids:
try:
ps = psutil.Process(pid)
name = ps.name()
except psutil.NoSuchProcess: # Catch the error caused by the process no longer existing
pass # Ignore it
else:
if "solitaire.exe" in name:
print(f"{name} running with pid: {pid}")
没有必要使用ps.pid
-它将具有与您用于初始化Process对象的pid
相同的值。此外,f-string(在Python 3.7+中可用)更易于阅读/维护,并且它们提供了一种更现代的方式来应用字符串格式化。