如何永远运行 Python 程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20170251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run the Python program forever?
提问by
I need to run my Python program forever in an infinite loop..
我需要在无限循环中永远运行我的 Python 程序。
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.sleepcall?
Any thoughts?
有没有更好的方法来做到这一点?或者我什至需要time.sleep打电话?有什么想法吗?
采纳答案by ubomb
Yes, you can use a while True:loop that never breaks to run Python code continually.
是的,您可以使用while True:永不中断的循环来持续运行 Python 代码。
However, you will need to put the code you want to run continually insidethe loop:
但是,您需要将要连续运行的代码放入循环中:
#!/usr/bin/python
while True:
# some python code that I want
# to keep on running
Also, time.sleepis used to suspendthe 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.
此外,time.sleep用于暂停脚本的操作一段时间。所以,既然你想让你的程序持续运行,我不明白你为什么要使用它。
回答by ubomb
It's one of the onlyways that I can think of. As to if it's appropriate, it depends on the use case - web servers and event loops sometimes do it like this. And no, you definitely do not need the time.sleep call.
这是我能想到的唯一方法之一。至于它是否合适,这取决于用例 - Web 服务器和事件循环有时会这样做。不,你绝对不需要 time.sleep 电话。
回答by roarsneer
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.
这将使您的程序休眠,直到它从某个其他进程(或它自己,在另一个线程中)接收到信号,让它知道是时候做某事了。
回答by gnr
for OS's that support select:
对于支持的操作系统select:
import select
# your code
select.select([], [], [])
回答by Porunga
sleep is a good way to avoid overload on the cpu
sleep 是避免 cpu 过载的好方法
not sure if it's really clever, but I usually use
不确定它是否真的很聪明,但我通常使用
while(not sleep(5)):
#code to execute
sleep method always returns None.
sleep 方法总是返回 None。
回答by Balaji.J.B
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
回答by Riaz Rizvi
I have a small script interruptableloop.pythat 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:
我有一个小脚本interruptableloop.py以间隔(默认为 1 秒)运行代码,它在运行时向屏幕输出一条消息,并捕获可以使用 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:
可中断循环.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 stop\t(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
回答by Edge Goldberg
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()

