How to run a script forever?

Question:

I need to run my Python program forever in an infinite loop..

Currently I am running it like this –

#!/usr/bin/python

import time

# some python code that I want 
# to keep on running


# Is this the right way to run the python program forever?
# And do I even need this time.sleep call?
while True:
    time.sleep(5)

Is there any better way of doing it? Or do I even need time.sleep call?
Any thoughts?

Asked By: user2467545

||

Answers:

Yes, you can use a while True: loop that never breaks to run Python code continually.

However, you will need to put the code you want to run continually inside the loop:

#!/usr/bin/python

while True:
    # some python code that I want 
    # to keep on running

Also, time.sleep is used to suspend the operation of a script for a period of time. So, since you want yours to run continually, I don’t see why you would use it.

Answered By: user2555451

How about this one?

import signal
signal.pause()

This will let your program sleep until it receives a signal from some other process (or itself, in another thread), letting it know it is time to do something.

Answered By: roarsneer

for OS’s that support select:

import select

# your code

select.select([], [], [])
Answered By: gnr

sleep is a good way to avoid overload on the cpu

not sure if it’s really clever, but I usually use

while(not sleep(5)):
    #code to execute

sleep method always returns None.

Answered By: Porunga

Here is the complete syntax,

#!/usr/bin/python3

import time 

def your_function():
    print("Hello, World")

while True:
    your_function()
    time.sleep(10) #make function to sleep for 10 seconds
Answered By: Balaji.J.B

I have a small script interruptableloop.py that runs the code at an interval (default 1sec), it pumps out a message to the screen while it’s running, and traps an interrupt signal that you can send with CTL-C:

#!/usr/bin/python3
from interruptableLoop import InterruptableLoop

loop=InterruptableLoop(intervalSecs=1) # redundant argument
while loop.ShouldContinue():
   # some python code that I want 
   # to keep on running
   pass

When you run the script and then interrupt it you see this output, (the periods pump out on every pass of the loop):

[py36]$ ./interruptexample.py
CTL-C to stop   (or $kill -s SIGINT pid)
......^C
Exiting at  2018-07-28 14:58:40.359331

interruptableLoop.py:

"""
    Use to create a permanent loop that can be stopped ...

    ... from same terminal where process was started and is running in foreground: 
        CTL-C

    ... from same user account but through a different terminal 
        $ kill -2 <pid> 
        or $ kill -s SIGINT <pid>

"""
import signal
import time
from datetime import datetime as dtt
__all__=["InterruptableLoop",]
class InterruptableLoop:
    def __init__(self,intervalSecs=1,printStatus=True):
        self.intervalSecs=intervalSecs
        self.shouldContinue=True
        self.printStatus=printStatus
        self.interrupted=False
        if self.printStatus:
            print ("CTL-C to stopt(or $kill -s SIGINT pid)")
        signal.signal(signal.SIGINT, self._StopRunning)
        signal.signal(signal.SIGQUIT, self._Abort)
        signal.signal(signal.SIGTERM, self._Abort)

    def _StopRunning(self, signal, frame):
        self.shouldContinue = False

    def _Abort(self, signal, frame):
        raise 

    def ShouldContinue(self):
        time.sleep(self.intervalSecs)
        if self.shouldContinue and self.printStatus: 
            print( ".",end="",flush=True)
        elif not self.shouldContinue and self.printStatus:
            print ("Exiting at ",dtt.now())
        return self.shouldContinue
Answered By: Riaz Rizvi

I know this is too old thread but why no one mentioned this

#!/usr/bin/python3
import asyncio 

loop = asyncio.get_event_loop()
try:
    loop.run_forever()
finally:
    loop.close()
Answered By: A J Brockberg

If you mean run as service then you can use any rest framework

from flask import Flask
class A:
    def one(port):
        app = Flask(__name__)
        app.run(port = port)
        

call it:

one(port=1001)

it will always keep listening on 1001

 * Running on http://127.0.0.1:1001/ (Press CTRL+C to quit)
Answered By: Akhilesh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.