Created
July 9, 2020 08:51
-
-
Save ramank775/59d02f83718c0919873fa7c3b48b8785 to your computer and use it in GitHub Desktop.
Get a process in python by name and port number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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