Monday, April 29, 2024
103
rated 0 times [  103] [ 0]  / answers: 1 / hits: 313150  / 1 Year ago, wed, january 4, 2023, 3:13:55

I am running a python program from a terminal in my Ubuntu machine as,



$ python test.py


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?


More From » command-line

 Answers
3

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.


[#27787] Thursday, January 5, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
intssive

Total Points: 493
Total Questions: 119
Total Answers: 101

Location: Liberia
Member since Mon, Feb 1, 2021
3 Years ago
intssive questions
Tue, Mar 21, 23, 08:19, 1 Year ago
Wed, Aug 31, 22, 04:04, 2 Years ago
Sat, Sep 25, 21, 15:09, 3 Years ago
Fri, Dec 31, 21, 09:13, 2 Years ago
;