16

I have a Python script which process data off of a HTTP data stream and I need this script to in theory be running at all times and forever unless I kill it off manually to update it and run it again.

I was wondering what the best practice to do this was on a Unix (Ubuntu in particular) so that even if Terminal is closed etc the script continues to run in the background unless the process or server are shut down?

Thanks

Mo.
  • 40,243
  • 37
  • 86
  • 131

4 Answers4

19

From your question you are implying that you are going to start the script from your terminal and not by any of Linux's startup script management methods like systemd or upstart or init.d scripts.

If you intend to start your script from terminal, and you want it to continue to run after you close your terminal, you need to do two things

1. Make it run in the background by appending '&' after your script.

2. When you close the terminal, the shell associated to it sends HUP signal to all the processes before it dying. To ignore the HUP signal and continue to run in the background you need to start your script with 'nohup'.

tl;dr
Run your script this way:

$ nohup python mypythonscript.py &
Ram
  • 488
  • 5
  • 13
10

Adding your script to rc.local would work, but 'best practice' in my opinion would be to use Upstart. See this post:

Daemon vs Upstart for python script

Community
  • 1
  • 1
Jorick Spitzen
  • 1,559
  • 1
  • 13
  • 25
6

It's an infinite loop. You can launch the script at startup and it will run forever until you kill the process itself or shut the computer down.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import time

while True:
    print 'Hello'
    time.sleep(2) # 2 second delay
Alex Ivanov
  • 695
  • 4
  • 6
  • 1
    This is not an answer to the question as the question was how to run the file and let it continue to run after the terminal window closes. – Peter Toth Nov 19 '21 at 21:05
2

I am not sure how "best practice" this is but you could do:

Add the program to: /etc/rc.d/rc.local

This will have the program run at startup.

If you add an '&' to the end of the line it will be run in the background.

If you dont want to run the program manually (not at startup) you could switch to another tty by pressing ctrl + alt + f1, (this opens tty1 and will work with f1 - f6) then run the command. This terminal you do not have to have open in a window so you dont have to worry about it getting closed. To return to the desktop use ctrl + alt + f7.

Robmotron
  • 354
  • 2
  • 8