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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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.
Method 3
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()
Method 4
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.
Method 5
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
Method 6
for OS’s that support select:
import select # your code select.select([], [], [])
Method 7
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
Method 8
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)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0