在后台+res中运行的Python无限循环脚本

2024-10-03 13:28:05 发布

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

我想要一个在后台运行的python脚本(无限循环)。在

def main():
    # inizialize and start threads
    [...]

    try:
        while True:
            time.sleep(1)

    except keyboardInterrupt:
        my.cleanup()

if __name__ == '__main__':
    main()
    my.cleanup()
  1. 为了让应用程序在无限循环中持续运行,最好的方法是什么?我想删除我不需要的time.sleep(1)

  2. 我想在后台运行脚本nohup python myscript.py &有没有办法“优雅地”终止它?当我正常运行它时,会调用CTRL+Cmy.cleanup(),那么在使用kill命令时有没有一种方法可以调用它?

  3. 如果我想(使用cron)终止脚本并重新启动它呢?有没有办法让它做到my.cleanup()

谢谢你


Tags: and方法脚本timemainmydefsleep
1条回答
网友
1楼 · 发布于 2024-10-03 13:28:05
  1. In order to have the application run constantly in infinite loop what is the best way? I want to remove the time.sleep(1) which I don't need

在我看来,while True或{}循环是可以的。在

只要不需要程序等待某个时间段,sleep()对于这样的无限循环不是必需的。在

  1. I would like to run the script in background nohup python myscript.py & is there a way to kill it "gracefully"? When I run it normally hitting the CTRL+C my.cleanup() is called, is there a way to call this when the kill command is used?

您可能希望使用signal()方法从包“signal”中“监听”几个信号。在

由信号挂钩扩展的简化示例:

import time
import signal

# determines if the loop is running
running = True

def cleanup():
  print "Cleaning up ..."

def main():
  global running

  # add a hook for TERM (15) and INT (2)
  signal.signal(signal.SIGTERM, _handle_signal)
  signal.signal(signal.SIGINT, _handle_signal)

  # is True by default - will be set False on signal
  while running:
    time.sleep(1)

# when receiving a signal ...
def _handle_signal(signal, frame):
  global running

  # mark the loop stopped
  running = False
  # cleanup
  cleanup()

if __name__ == '__main__':
  main()

注意,您不能监听SIGKILL,当使用该信号终止一个程序时,您没有机会进行任何清理。你的程序应该意识到这一点(做一种预启动清理或失败的消息)。在

注意,我使用了一个全局变量来保持这个例子的简单性,我更喜欢将它封装在一个自定义类中。在

  1. What if I would like (using cron) kill the script and restart it again? Is there a way to make it do my.cleanup()?

只要你的cronjob会用除SIGKILL之外的任何信号终止程序,这当然是可能的。在

你应该考虑用不同的方式来做你想做的事情:例如,如果你想在无限循环任务之前“重做”一些设置任务,你也可以在某个信号上这样做(例如,有些程序使用SIGHUP来重新加载配置)。你必须打破循环,完成任务,然后继续。在

相关问题 更多 >