How to run the Python program forever?

user2467545 picture user2467545 · Nov 24, 2013 · Viewed 259.8k times · Source

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?

Answer

user2555451 picture user2555451 · Nov 24, 2013

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.