Finding the command for a specific PID in Linux from Python

后端 未结 7 889
半阙折子戏
半阙折子戏 2020-12-19 05:33

I\'d like to know if it\'s possible to find out the \"command\" that a PID is set to. When I say command, I mean what you see in the last column when you run the command \"t

7条回答
  •  失恋的感觉
    2020-12-19 06:22

    An interesting Python package is psutil.

    For example, to get the command for a specific PID:

    import psutil
    pid = 1234 # The pid whose info you're looking for
    p = psutil.Process(pid)
    print p.cmdline
    

    The last line will print something like ['/usr/bin/python', 'main.py'] .

    A more robust way to get this information, being careful if the pid represents a process no longer running:

    import psutil
    pid = 1234 # The pid whose info you're looking for
    if pid in psutil.get_pid_list():
        p = psutil.Process(pid)
        print p.cmdline
    

提交回复
热议问题