Solve the problem that the port is occupied after the flask restarts (non-kill method)

Problem Description

In my flask program, I start another python program - test.py:

os.system('nohup python /opt/test/test.py >/dev/null 2>&1 &')

When I end the flask program and start it again, it will report an error that the port is occupied:

Port 5000 is already in use

And the program that occupies my 5000 port is exactly the test.py program I run in flask


Solution 1: Kill the process that occupies the port

First run the netstat command to find the pid that occupies port 5000, then kill the process, and start flask again

netstat -npl |grep 5000
tcp        0      0 1xx.1xx.xx.xx:5000      0.0.0.0:*               LISTEN      9345/python
kill -9 9345

Basically, this method is copied and pasted in different ways on the Internet. Although it can solve the problem, the test.py program I originally started will have to be killed. Obviously, this does not solve the fundamental problem.

Solution 2: Switch to the submission method of the python command

The key to our current problem is why the program I started in flask will always occupy our port number. After continuous experimentation, I finally found the problem: the reason why the port number is occupied is because we used the submission command:

os.system('nohup python /opt/test/test.py >/dev/null 2>&1 &')

Submitting with os.system, we can understand that the running test.py program is a sub-process managed by the flask process, so when the flask ends, this sub-process will still occupy my 5000 port number.

Therefore, we submit it in the following way instead:

subprocess.Popen('nohup python /opt/test/test.py >/dev/null 2>&1 &', shell=True)

subprocess is a new module in Python 2.4, which allows you to generate new processes, which has nothing to do with the flask process, so it fundamentally solves the problem of port occupation.

subprocess

Guess you like

Origin blog.csdn.net/bradyM/article/details/126425835