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

2024-09-30 08:15:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python程序需要全天候运行。它有10%的时间在30秒的间隔内睡着。有没有办法让程序安全地停止并重新启动,以便只在睡眠期间重新启动?你知道吗

以下是代码示例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()

Tags: 函数代码程序true示例间隔timemain
1条回答
网友
1楼 · 发布于 2024-09-30 08:15:32

一种方法是将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/之类的东西使程序在启动时进行后台监控。你知道吗

然后,要在下次睡眠时重新启动程序,只需触摸重新启动文件。您可以在配置文件中将其路径设置为任何您喜欢的路径。你知道吗

相关问题 更多 >

    热门问题