python脚本无法作为守护程序运行(EOFError:读取行时的EOF)

问题描述 投票:0回答:1

我已经创建了一个在命令行上运行良好的python3脚本但是当我尝试在MacosX中作为守护进程运行时,在读取一行时会出现错误'EOFError:EOF'。基本代码如下:

  (...)

  def main():

    # Connect
    port, speed = connect_port()

    device = XBeeDevice(port, speed)

    try:
      device.open()
      # print("Waiting for data...\n")

     (...)

      device.add_packet_received_callback(packet_received_callback)
      input()

    finally:
      if device is not None and device.is_open():
        device.close()

  if __name__ == '__main__':
    main()

plist似乎很好,因为脚本启动并运行一次之前给出错误:

Traceback (most recent call last):
File "/maslestorres.cat/jardiNet_datalogger.py", line 214, in <module>
main()
File "/maslestorres.cat/jardiNet_datalogger.py", line 206, in main
input()
EOFError: EOF when reading a line

所以基本上我不知道如何调整input()行以允许作为守护进程运行。 Python是版本3.7.2,MacOSX是10.8.5。

python python-3.x macos launchd
1个回答
0
投票

就其本质而言,守护进程无法从控制台进行input()。你需要另一种方法来无限期地暂停主线程,同时让XBee PacketListener thread继续运行回调。

实现这一目标的最简单方法是将input()替换为:

while True:
    time.sleep(1000000)    # arbitrarily large number

在关闭时,系统的服务管理器将停止您的守护程序:

  • 通过发送SIGTERM - 在这种情况下你的守护进程将立即终止,而不执行finally块;
  • 或者通过发送SIGINT - 在这种情况下,KeyboardInterrupt例外将从time.sleep(1000000)冒出来,并且finally块将运行。

无论哪种情况,您的流程都应该快速停止。

为了更正确的解决方案,能够优雅地处理SIGTERM,请看这里:https://stackoverflow.com/a/46346184/200445

© www.soinside.com 2019 - 2024. All rights reserved.