我想要一个在后台运行的python脚本(无限循环)。在
def main():
# inizialize and start threads
[...]
try:
while True:
time.sleep(1)
except keyboardInterrupt:
my.cleanup()
if __name__ == '__main__':
main()
my.cleanup()
为了让应用程序在无限循环中持续运行,最好的方法是什么?我想删除我不需要的time.sleep(1)
我想在后台运行脚本nohup python myscript.py &
有没有办法“优雅地”终止它?当我正常运行它时,会调用CTRL+Cmy.cleanup()
,那么在使用kill命令时有没有一种方法可以调用它?
如果我想(使用cron)终止脚本并重新启动它呢?有没有办法让它做到my.cleanup()
?
谢谢你
在我看来,}循环是可以的。在
while True
或{只要不需要程序等待某个时间段,
sleep()
对于这样的无限循环不是必需的。在您可能希望使用
signal()
方法从包“signal
”中“监听”几个信号。在由信号挂钩扩展的简化示例:
注意,您不能监听
SIGKILL
,当使用该信号终止一个程序时,您没有机会进行任何清理。你的程序应该意识到这一点(做一种预启动清理或失败的消息)。在注意,我使用了一个全局变量来保持这个例子的简单性,我更喜欢将它封装在一个自定义类中。在
只要你的cronjob会用除
SIGKILL
之外的任何信号终止程序,这当然是可能的。在你应该考虑用不同的方式来做你想做的事情:例如,如果你想在无限循环任务之前“重做”一些设置任务,你也可以在某个信号上这样做(例如,有些程序使用
SIGHUP
来重新加载配置)。你必须打破循环,完成任务,然后继续。在相关问题 更多 >
编程相关推荐