ScanSkill
Sign up for daily dose of tech articles at your inbox.
Loading

How To Run Python Script Forever ?

How To Run Python Script Forever ?
How To Run Python Script Forever ?

Either it is a simple web application or complex code written in python, at some point in time you will want to make your python script run forever. In this article, we are going to learn different ways to make our python code run forever or whatever time we need.

nohup

Source : ComputerHope.com

NoHup stands for no hang-up, which is a command on a unix-like system. nohup is used to execute another command and instruct system to continue running that command even if the session or terminal is closed. The way nohup works is that it prevents the jobs or processes whichever running inside it to receive the SIGHUP – signal hang up signal. This is the same signal which is broadcasts to a job when there is exit on signal or terminal. Basic nohup syntax looks like this :nohup command [command-argument …]nohup –help | –version

Now, let’s see how can we use this nohup command to keep our python script running on background.nohup python /path/to/script.py &

Above command will run any python script and logs the output on nohup.out file created on same directory. But if you want to log the output somewhere else rather than default then run the following command with your preferred file for output.nohup python /path/to/script.py output.log &

pm2

pm2 to run python code forever

pm2 is another way to make python code running on background. As stated on official site :

PM2 is daemon process manager that will help you manage and keep your application online. Getting started with PM2 is straightforward, it is offered as a simple and intuitive CLI, installable via NPM.

pm2

One thing we need to take care here is that pm2 is node package and to make our python code run through pm2 we also must install couple of dependency (Node , pm2 ) on our system. To install them run the following commands.

Node
To install node, please follow the official documentation from here.

pm2
To install pm2, run the following command on terminal.
Note : node must be installed before this.

npm install -g pm2@latest

Now, after installation of pm2, to run python script forever on background, here is the simpler approach that will work.

pm2 start path/to/script.py --interpreter=python

Hope it helped to run python script forever, we will be covering usage of pm2 in detail on upcoming days. Keep visiting us.

Sign up for daily dose of tech articles at your inbox.
Loading