I have a python script where I use a listener from another library to wait and listen for an event to occur (that my script then handles). In development, I used an input() statement (inside a while True loop) at the end of my script to efficiently keep the script alive while doing nothing (other than waiting for the event). However, now that I've put this into a systemd service, the input() fails with an EOF since system services are not expected to have any console IO. What is a 'nice' or pythonic way to achieve essentially an endless loop here? I could do a while True: pass
or while True: sleep(0.1)
but the first burns the CPU, while the second seems hackish.
Asked
Active
Viewed 332 times
-1

askvictor
- 3,621
- 4
- 32
- 45
-
I think this thread might help you in your efforts https://stackoverflow.com/questions/20170251/how-to-run-the-python-program-forever – Aman Raparia Jan 04 '19 at 09:44
1 Answers
1
Have a look at official document about coroutines.
Example:
import time, asyncio
async def run_task():
for i in range(5):
print('running task %d' % i)
await awaiting_task(i)
async def awaiting_task(name):
time.sleep(5) # wait for 5 seconds
print('task %s finished' % str(name))
asyncio.run(run_task())
The async
syntax will turn the function to a coroutine, which saves your cpu if possible, other than busy waiting.

knh190
- 2,744
- 1
- 16
- 30