在睡眠期间安全地重新启动 python 程序?

Restarting a python program during sleep safely?

我有一个 python 程序需要 运行 24/7。它以 30 秒的间隔大约有 10% 的时间处于睡眠状态。有没有办法让程序安全地停止并再次启动,以便仅在睡眠期间重新启动?

这里是代码示例,main() 函数和实现:

# =============================================================================
# MAIN
# =============================================================================

def main():
    while True:
        checkReply = Reply()
        checkReply.time_to_reply()
        checkReply.search_db()
        time.sleep(10)


# =============================================================================
# RUNNER
# =============================================================================
print "start"
if __name__ == '__main__':
    main()

一种方法是将您的 main() 更改为如下所示:

def main():
    restart_file = config.get('some_section', 'restart_file')
    while True:
        checkReply = Reply()
        checkReply.time_to_reply()
        checkReply.search_db()
        time.sleep(10)
        if os.path.exists(restart_file):
            os.unlink(restart_file)
            if 0 == os.fork():
                os.execl(shlex.split('command to run the updated program'))
            sys.exit('restarting')

为了增加功劳,请使用 https://pypi.python.org/pypi/python-daemon/ 之类的东西让您的程序在启动时自行守护进程。

然后,要在下次休眠时重新启动您的程序,您所要做的就是触摸重新启动文件。您可以在配置文件中将其路径设置为您喜欢的任何内容。