Search code examples
pythonprocessportpid

How to get a process instance (with pid or listening port) in Python?


In Python, subprocess.Popen(cmd) can return a subprocess.Popen instance, which represents a process with certain cmd. I'm wondering, is it possible to get such an instance by the port that the process listens to, or by the pid of the process?

For example, is there an API such as subprocess.getProcessesByPort(port) or subprocess.getProcess(pid)?

I understand such flexibility might cause security problems and will not be surprised if this is impossible. I didn't use this module before and want to look for more insights for it.

Thanks in advance!


Solution

  • psutil package might provide what you want in a cross-platform manner.