如何永远运行Python程序?


问题内容

我需要在无限循环中永远运行我的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)

有什么更好的方法吗?还是我甚至需要time.sleep打电话?有什么想法吗?


问题答案:

是的,您可以使用一个while True:永不中断的循环来连续运行Python代码。

但是,您需要将要连续运行的代码 放入 循环中:

#!/usr/bin/python

while True:
    # some python code that I want 
    # to keep on running

另外,time.sleep用于将脚本的操作
暂停 一段时间。因此,由于您希望自己的设备连续运行,所以我不明白为什么要使用它。