Skip to content

Instantly share code, notes, and snippets.

@ramank775
Created July 9, 2020 08:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramank775/59d02f83718c0919873fa7c3b48b8785 to your computer and use it in GitHub Desktop.
Save ramank775/59d02f83718c0919873fa7c3b48b8785 to your computer and use it in GitHub Desktop.
Get a process in python by name and port number
import psutil
def get_process_by_name_port(process_name, port):
processes = [proc for proc in psutil.process_iter() if proc.name()
== process_name]
for p in processes:
for c in p.connections():
if c.status == 'LISTEN' and c.laddr.port == port:
return p
return None
process_python_8080 = get_process_by_name_port('python.exe', port)
print("PID", process_python_8080.pid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment