Search code examples
pythonlinuxdiscord.pyprawpsutil

How to find out the psid of a running python script by name?


I am working with discord.py and praw. The script is supposed to terminate another script by the name of 'r5bot.py' (which is running in the background via nohup) whenever the discord bot receives a message '!kill bot' and start it if the message is '!start bot'. For that I need to find out the psid of the 'r5bot.py' script by name because it will be constantly changing. How to do that?

I tried using psutil but it doesn't seem to be working.

program_name = 'r5bot.py'
process_pids = [process.pid for process in psutil.process_iter() if process.name == program_name]
print(process_pids)  # e.g [1059, 2343, ..., ..., 9645]

But it never prints anything. What am I doing wrong?


Solution

  • It might be better searching the whole command line, as r5bot.py might not be the process name:

    import psutil
    
    program_name = 'r5bot.py'
    process_pids = [
        process.pid
        for process in psutil.process_iter() if program_name in process.cmdline()
    ]
    print(process_pids)
    

    Out:
    [31959, 32011, 32055, 32098]