Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a script forever? [duplicate]

People also ask

How do I keep scripts running forever?

The simplest way to keep a program running “forever” is to put your code in a while loop and set the condition to True.

How do you do a loop forever in Python?

For certain situations, an infinite loop may be necessary. A very basic way of creating an infinite loop in Python is to use a while statement. This is shown below. This goes on forever and ever, unless the program is terminated.


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.


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.


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()

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.