0

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) )

dskrypa
  • 1,004
  • 2
  • 5
  • 17
Mr Diga
  • 3
  • 4

1 Answers1

1

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.

dskrypa
  • 1,004
  • 2
  • 5
  • 17
  • thanks , this fixed my problem , but i have a question , may i add " for pid in pids: " under try: too ? putting the whole code under try: ? – Mr Diga Nov 13 '22 at 23:30
  • You should limit the content of what is inside of a `try:` block to only the code may raise what your `except` clause intends to catch. If the `for pid in pids:` line was inside the try block, then it would only be able to handle one exception for the entire loop. This implementation will handle the exception for each iteration of the loop, so that it will continue to try additional pids. You can find more here: https://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else-in-python – dskrypa Nov 13 '22 at 23:38