Get python process ID for a flask web site and/or port number?
8,410
Solution 1
You can use lsof
to find the process id associated with a known port number
lsof -i :*port*
Alternatively, you may wish to use netstat
which can display all network connections, routing tables, interface statistics, masquerade connections, and multicast memberships.
Try netstat -tulpn
Solution 2
One other way is to add it to the flask app itself.
from os import getpid
print("Creating PID file.")
fh=open("/var/run/yourAppNameWithPort.pid", "w")
fh.write(str(getpid()))
fh.close()
Related videos on Youtube
Author by
Unknown Coder
Updated on September 18, 2022Comments
-
Unknown Coder over 1 year
I have some web applications that I wrote with python flask. I know which port I started each one on and each was started using nohup. Each one was started with something like
nohup python mywebapp.py &
When I look at my processes with
ps
, I only see something like36697 ? 60-21:36:16 python 36971 ? 63-19:11:43 python 37038 ? 65-06:57:22 python 37312 ? 54-23:33:16 python 37442 ? 54-09:14:57 python 37716 ? 47-19:45:17 python 68019 ? 00:29:24 python 146568 ? 00:20:57 python 146699 ? 00:17:08 python 150622 ? 00:32:20 python
If I need to stop one particular web application, how can I get from a port number back to a python process id so that I can
kill
the process?-
Jeff Schaller almost 6 yearswhere does the port number get specified when you start(ed) them?
-
Unknown Coder almost 6 years@JeffSchaller Great question, that is specified within the python code, specifically with a call to start an app server with the flask library/framework.
-
Jeff Schaller almost 6 yearsSo the parameter
mywebapp.py
is enough to determine the port?
-
-
Unknown Coder almost 6 yearsThis sounds like its along the right track but this server does not have lsof and I cant use apt-get. Are there any other commands similar to this that you would recommend?
-
Unknown Coder almost 6 yearsIs this something I would do before I startup the app or can I do it even while the app is running?
-
Tyler Chambers almost 6 yearsif you have
netstat
you may be able to find it usingnetstat -tulpn
. You may have to grep the output for it to be useful. -
Unknown Coder almost 6 yearsThat did it, thank you! I can see the ports and then it gives me the PID in the last column, this is perfect!
-
Joe M almost 6 yearsYou'd add this to you app, it would happen on startup. I usually use argparse and pass in the pidfile name as an argument, but that is just my preference.