0

I have a simple python script I run on linux that has a "while True:" loop that I run on startup. I need it to run constantly. I currently just add & to the end of the linux command line when starting it. Is there a simple way to have if fork rather then have too use the & when I run it?

import socket
import sys
from datetime import datetime
import os


while True:
   print "hi", "there"
   sleep(100000)
   #do stuff

I primarily want to just detach my script from the tty so the user can exit the tty and it continues to run.

Matt
  • 57
  • 1
  • 2
  • 9
  • 1
    If you're waiting 100 seconds you really want a `cron` job. If you want it in the background look for a "daemon" library. If your system uses `systemd` it's pretty easy to write a config file that will help launch, supervise, and reboot this process if it crashes. – tadman Jul 13 '17 at 15:16
  • You could probably run it as a systemd startup script ("service unit") https://unix.stackexchange.com/questions/47695/how-to-write-startup-script-for-systemd – pj_gineste Jul 13 '17 at 15:17
  • `os.fork`, or use threads. – cs95 Jul 13 '17 at 15:17
  • 1
    Possible duplicate of [How to make a Python script run like a service or daemon in Linux](https://stackoverflow.com/questions/1603109/how-to-make-a-python-script-run-like-a-service-or-daemon-in-linux) – dlmeetei Jul 13 '17 at 15:27
  • Following the suggestion here posted above: https://stackoverflow.com/a/1603152/7802443 I simply added fpid = os.fork() and if fpid!=0: sys.exit(0) above my while loop. It seems to work fine for what I wanted. – Matt Jul 13 '17 at 19:20

1 Answers1

0

There is python daemon library, https://pypi.python.org/pypi/python-daemon/ But it is more trouble that required. Your best bet is to use a cron job to achieve this functionality.

If you do try to fork this, this answer will explain how to do this.

Palash Goel
  • 624
  • 6
  • 17