Open In App

Running Python program in the background

Improve
Improve
Like Article
Like
Save
Share
Report

Let us see how to run a Python program or project in the background i.e. the program will start running from the moment device is on and stop at shut down or when you close it. Just run one time to assure the program is error-bug free

One way is to use pythonw, pythonw is the concatenation of python+without terminal window, i.e. run python without terminal window. You can use it by running the following line on the terminal:

pythonw <nameOfFile.py>

Here’s the background.py is the file:

In Linux and mac, for running py files in the background you just need to add & sign after using command it will tell the interpreter to run the program in the background  

python filename.py & 

It will run the program in the background also simultaneously you can use a terminal. There will process id for the background process, if you want you can kill process also by using as you can’t just kill it by CTRL+C , To kill it, open another terminal session and use the command

kill -9 {{id got after }} &

kill is abbreviated for killing process while -9 used to tell to kill it immediately, the corresponding status will be updated. In order to get your output, you can flush it up in a file  by using 

python filename.py > filenameToFlush &

It will be generating output i.e. flushing output in the file but it’s updated in the buffer memory, you have to wait for the termination of the program to reflect output in a hard disk file. To resolve this, you just need to tell python interpreter that don’t use buffered memory steps:

End/kill currently running the file

Now use utility 

 python -u filename.py > FileToFlush &

It will directly put the output in the file you have selected.

If you close terminal before the end of the program, all processes executed by the terminal will stop, A hangup situation is arising in order to counter problem you need to use nohup command as shown below nohup will assure that process is running till the end whether you close parent terminal. nohup stands for no hangup 

nohup python -u filename.py 

Now you don’t need to flush output in any file as nohup utility generates a file named nohup.out while executing. It will be like log file. The name of the output fill generated by nohup will reflect on. To terminate this execution you will need ID process, There is no problem if you can remember or if you can’t, you need to search for file Just use following command

ps ax | grep filename.py

grep is for pattern searching, it will be reflecting process id on terminal just kill it by using kill -9 ID. Now the process is terminated


Last Updated : 21 Aug, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads