SSH SSH - 1 month ago 12
Python Question

How to run the Python program forever?

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

Currently I am running it like this -

#!/usr/bin/python


# 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

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.