Python - 无限循环脚本 运行 在后台 + 重启

Python - Infinite loop script running in background + restart

我想要一个 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 & 有没有办法杀死它 "gracefully"?当我 运行 它通常点击 CTRL+C my.cleanup() 被调用,有没有办法在使用 kill 命令时调用它?

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

谢谢

  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 Truewhile <condition> 循环是可以的。

A 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?

您可能想 "listen" 使用包“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,当使用该信号终止程序时,您没有机会进行任何清理。您的程序应该意识到这一点(做一种启动前清理或失败并显示正确的消息)。

注意,我使用了一个全局变量来简化这个例子,我更喜欢将它封装在自定义 class.

  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 以外的任何信号终止程序,这当然是可能的。

你应该考虑以不同的方式做你想做的事情:例如,如果你想 "re-do" 在无限循环任务之前进行一些设置任务,你也可以在某个信号(例如,某些程序使用 SIGHUP 来重新加载配置)。您必须打破循环,执行任务并恢复它。