后台多线程 Python 应用程序
Multithreaded Python application in background
我在 Raspberry Pi 上有一个 Python 应用程序 myapp,前端控制面板是用 Dash 制作的。我 运行 Dash 应用程序在它自己的线程中,这样我就可以用它来操作 myapp.
中的一些设置
当我通过 SSH 连接到 Raspberry Pi 时,我想在后台启动 Python 应用程序 myapp,然后关闭远程 [=36] =] window 让它旋转并做它的事情。写完这个问题后,我发现我必须根据
使用 nohup
nohup python path/to/myapp.py &
对于其他 python 应用,只需
python path/to/other_app &
好像够了。
所以我想我已经有了问题的答案。但是,在这个问题上,这是首选且唯一的解决方案吗?
这在很大程度上取决于您 运行 使用的具体 linux 变体,但一般来说,最好的方法是让系统的服务管理器处理它。现在大多数情况下,这意味着 systemd。
创建服务配置文件-
[Unit]
Description=My Python Service
[Service]
Type=simple
ExecStart=/path/to/my/python/service.py
[Install]
WantedBy=multi-user.target
- 将其放在
/lib/systemd/system/
中,名称类似于 mypythonapp.service
。
- 运行
systemctl daemon-reload
这样 systemd 就知道要查找新文件了。
- 运行
systemctl enable mypythonapp.service
在启动时告诉它 运行 应用程序。
- 运行
systemctl start mypythonapp.service
立即告诉 运行 应用程序。
现在您的脚本将有日志记录,当崩溃或系统重新启动时将重新启动,您不必手动启动它。
我在 Raspberry Pi 上有一个 Python 应用程序 myapp,前端控制面板是用 Dash 制作的。我 运行 Dash 应用程序在它自己的线程中,这样我就可以用它来操作 myapp.
中的一些设置当我通过 SSH 连接到 Raspberry Pi 时,我想在后台启动 Python 应用程序 myapp,然后关闭远程 [=36] =] window 让它旋转并做它的事情。写完这个问题后,我发现我必须根据
使用 nohupnohup python path/to/myapp.py &
对于其他 python 应用,只需
python path/to/other_app &
好像够了。
所以我想我已经有了问题的答案。但是,在这个问题上,这是首选且唯一的解决方案吗?
这在很大程度上取决于您 运行 使用的具体 linux 变体,但一般来说,最好的方法是让系统的服务管理器处理它。现在大多数情况下,这意味着 systemd。
创建服务配置文件-
[Unit]
Description=My Python Service
[Service]
Type=simple
ExecStart=/path/to/my/python/service.py
[Install]
WantedBy=multi-user.target
- 将其放在
/lib/systemd/system/
中,名称类似于mypythonapp.service
。 - 运行
systemctl daemon-reload
这样 systemd 就知道要查找新文件了。 - 运行
systemctl enable mypythonapp.service
在启动时告诉它 运行 应用程序。 - 运行
systemctl start mypythonapp.service
立即告诉 运行 应用程序。
现在您的脚本将有日志记录,当崩溃或系统重新启动时将重新启动,您不必手动启动它。