I have this code for getting PIDs for specific processes; the code is running well, but sometimes I get this error:
psutil.NoSuchProcess: Process no longer exists (pid=xxxx)
How can this problem be solved? And how can I restart the script if this error or other errors happened?
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) )
CodePudding user response:
The problem is that between discovering the pid (process ID) of a given program and the loop getting to the point where it attempts to inspect it, that process has already stopped running.
You can work around it by using 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}")
There's no need to use ps.pid
- it will have the same value as the pid
you used to initialize the Process object. Additionally, f-strings (available in Python 3.7 ) are easier to read/maintain, and they provide a more modern way to apply string formatting.