python - python script fails running as a daemon (EOFError: EOF when reading a line)
问题描述
I've created a python3 script that runs fine on command line but when I try to run as a daemon in MacosX gives error 'EOFError: EOF when reading a line'. Basically code is as follows:
(...)
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 seems to be fine as script starts and runs once before to give error:
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
So basically I don't know how to adapt the input() line to allow to run as a daemon. Python is version 3.7.2 and MacOSX is 10.8.5.
解决方案
就其本质而言,守护进程不能input()
来自控制台。您需要另一种方法来无限期地挂起主线程,同时让 XBeePacketListener
线程继续运行回调。
完成此操作的最简单方法是替换input()
为:
while True:
time.sleep(1000000) # arbitrarily large number
当需要关闭时,系统的服务管理器将停止您的守护进程:
- 要么通过发送
SIGTERM
——在这种情况下,你的守护进程将立即终止,而不执行finally
块; - 或者通过发送
SIGINT
——在这种情况下,一个KeyboardInterrupt
异常会从 中冒出来time.sleep(1000000)
,并且该finally
块将运行。
无论哪种情况,您的进程都应该快速停止。
有关更正确的解决方案,也能够SIGTERM
优雅地处理,请参见此处:https ://stackoverflow.com/a/46346184/200445
推荐阅读
- authentication - 主动和被动指纹识别有什么区别?
- php - 如何在 laravel 中使用忽略来验证名称
- xcode - 即使安装了“Xcode Version 11.2.1 (11B500)”,Xcode 仍然会导致使用 UITextView 的应用程序崩溃
- docker - 保存凭据时出错:存储凭据时出错 - 错误:没有凭据服务器 URL,输出:登录 docker 时“没有凭据服务器 URL”
- php - 如何用php替换大量重复字母中的字母?
- ssl - Digital Ocean CyberPanel(在 Ubuntu 18.04 上):ACME 证书被阻止禁止 - 283 无法为域获取 SSL。[问题SSLForDomain]
- powershell - 如何更改 PowerShell 提示颜色?
- javascript - 如何键入返回对象的常量函数?
- batch-file - 如何从服务获取响应消息并使用批处理文件打印该消息?
- c++ - 运算符重载 - [错误] ld 返回 1 个退出状态