How to run a python program in the background even after closing the terminal? [duplicate]

But my whole program will be stopped if I close the terminal, Is there any way of running this python program in the background so that if I close my terminal then it still keeps on running? And also after running this program in the background, how do I find out my actual program whether it is still running or not if I am logging back again to that terminal?

45.3k 21 21 gold badges 105 105 silver badges 129 129 bronze badges asked Dec 28, 2013 at 3:19 2,023 8 8 gold badges 24 24 silver badges 23 23 bronze badges See here: askubuntu.com/questions/106351/… should answer your question. Also a possible duplicate. Commented Dec 28, 2013 at 3:21

And, when you run a program in the background with & , it will print a PID that you can search for with something like ps aux | grep PID .

Commented Dec 28, 2013 at 3:22 @Seth Yes, that puts it in the background, but when the terminal is quit, the program goes away too. Commented Dec 28, 2013 at 3:23 @Seth: Everytime I do need to remember the PID to look for the process? Commented Dec 28, 2013 at 3:23 @TechGeeky Yes. Commented Dec 28, 2013 at 3:24

2 Answers 2

Use the shebang line in your python script. Make it executable using the command,

chmod +x test.py 

Use no hangup to run the program in the background even if you close your terminal,

nohup /path/to/test.py & 

or simply (without making any change in your program)

nohup python /path/to/test.py & 

Do not forget to use & to put it in the background.

Role of nohup : nohup makes your script ignore SIGHUP , and redirects stdout/stderr to a file nohup.out, so that the command can continue running in the background after you log out. If you close the shell/terminal or log off, your command is no longer a child of that shell. It belongs to init process. If you search in pstree you'll see it is now owned by process 1 (init).

To see the process again, use in terminal,

ps ax | grep test.py 

That cannot be brought back to the foreground because the foreground (as the terminal already closed) no longer exists. So there is no way to get that terminal back again once it is closed.