Running a Python File in the Background with nohup
When running a Python file on the backend, such as a Flask or FastAPI application, it’s often necessary to keep the process running in the background even after the user logs out. One way to do this is by using the nohup command.
The nohup command stands for “no hangup”, and it allows you to run a command or script that continues running even after you log out of the terminal. This is useful for running long-running processes like a web server or a machine learning training script.
Here’s how to use nohup to run a Python file in the background:
- Create a log file to capture any output from the script. You can do this using the touch command:
touch nohup.out
This will create an empty file called nohup.out in the current directory.
- Run the Python file using the nohup command, followed by the & symbol to run the command in the background:
nohup python3 app.py &
This will start the app.py file in the background, and any output from the script will be redirected to the nohup.out file.
- If you want to monitor the output of the script in real-time, you can use the tail command to follow the nohup.out file:
tail -f nohup.out
This will display the last few lines of the file, and any new output will be added to the display as it becomes available.
Killing a Process Started with nohup
If you need to stop the Python process that you started with nohup, you’ll need to find the process ID (PID) and kill the process. Here’s how to do it:
- Use the ps command to find the PID of the Python process:
ps -ef | grep app.py | grep -v grep
This will display a list of all running processes that match the name app.py. The grep -v grep option is used to exclude the grep command itself from the output.
- Once you’ve identified the PID of the process, you can use the kill command to send a signal to the process to stop:
kill PID
Replace PID with the actual process ID. This will send a SIGTERM signal to the process, allowing it to do any cleanup work before terminating.
- If the process does not terminate after a few seconds, you can try sending a SIGKILL signal instead:
kill -9 PID |
This will force the process to terminate immediately, without giving it a chance to do any cleanup work.
Conclusion
Using nohup to run a Python file in the background is a useful technique for running long-running processes on a server. By redirecting output to a log file, you can monitor the progress of the process and troubleshoot any issues that may arise.
If you need to stop the process, you can use the ps and kill commands to find and terminate the process. By using these commands carefully, you can ensure that your system remains stable and secure.