我需要在无限循环中永远运行我的Python程序.
目前我正在运行它 -
#!/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)
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?或者我甚至需要time.sleep
打电话?有什么想法吗?
iCo*_*dez 84
是的,您可以使用while True:
永不中断的循环来持续运行Python代码.
但是,您需要将要在代码中连续运行的代码放在循环中:
#!/usr/bin/python
while True:
# some python code that I want
# to keep on running
Run Code Online (Sandbox Code Playgroud)
此外,time.sleep
用于暂停脚本的操作一段时间.所以,既然你希望你的不断运行,我不明白你为什么要使用它.
roa*_*eer 28
这个怎么样?
import signal
signal.pause()
Run Code Online (Sandbox Code Playgroud)
这将让你的程序睡眠,直到它收到来自其他进程(或自身,在另一个线程)的信号,让它知道是时候做某事了.
Edg*_*erg 16
我知道这太旧了,但为什么没有人提到这一点
#!/usr/bin/python3
import asyncio
loop = asyncio.get_event_loop()
try:
loop.run_forever()
finally:
loop.close()
Run Code Online (Sandbox Code Playgroud)
睡眠是避免CPU过载的好方法
不知道它是否真的很聪明,但是我通常使用
while(not sleep(5)):
#code to execute
Run Code Online (Sandbox Code Playgroud)
sleep方法始终返回None。
小智 6
这是完整的语法,
#!/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
Run Code Online (Sandbox Code Playgroud)
对于操作系统的支持select
:
import select
# your code
select.select([], [], [])
Run Code Online (Sandbox Code Playgroud)