Search code examples
pythonpython-3.xexceptionpsutil

how to capture the error code or error message from psutil


I have a sample python3 code below, and want to capture what kinds of error when calling psutil functions. However after running the code below, it only prints out the Error: <class 'psutil.Error'>.

How can I capture the real meaningful error message here? Thanks.

import psutil

pid = 12345

try:
    p = psutil.Process(pid)
    p.terminate()
except psutil.Error:
    print("Error: ", psutil.Error)

Solution

  • You need to assign the error to a variable on the end of your except statement, like this:

    import psutil
    
    pid = 12345
    
    try:
        p = psutil.Process(pid)
        p.terminate()
    except psutil.Error as error:
        stringerror = str(error)
        print ("Error: " + stringerror)
    

    I've also converted the error statement variable to a string at the end so the output here is as you intended, this avoids a TypeError with concantenation.