免费自媒体网站有创意的设计公司名称
news/
2025/9/26 11:23:50/
文章来源:
免费自媒体网站,有创意的设计公司名称,外贸soho东莞建站,wordpress隐私页1. 使用 systemd 服务设置开机自启动
假设已经有一个可执行的python程序#xff0c;然后用一个sh脚本去启动python程序#xff0c;正常情况使用挂起的方式nohup启动#xff0c;日志输出到指定文件#xff1a;
sudo touch run.sh
sudo chmod 777 run.shsh文件内容如下然后用一个sh脚本去启动python程序正常情况使用挂起的方式nohup启动日志输出到指定文件
sudo touch run.sh
sudo chmod 777 run.shsh文件内容如下-u可以把print的打印也输出到nohup.log文件中使用./run.sh即可在后台运行python程序
#! /bin/bash
nohup /usr/bin/python3 -u test.py nohup.log 21 在/etc/systemd/system目录下创建一个service文件文件内容如下
[Unit]
DescriptionMy Python Program
Afternetwork.target[Service]
Typesimple
ExecStart/path/to/your/sh/run.sh
WorkingDirectory/path/to/working/directory
Useryour_user
Groupyour_group
EnvironmentPYTHONPATH/path/to/python/lib
Restarton-failure[Install]
WantedBymulti-user.target重新加载 systemd 配置
sudo systemctl daemon-reload设置开机自启服务
sudo systemctl enable my_program.service立即启动服务
sudo systemctl start my_program.service查看服务状态
sudo systemctl status my_program.service查看系统日志 -f 可以查看实时日志
journalctl -f -u your_service_name.service系统日志太多时可以删除旧日志比如清除1天之前的日志
journalctl --vacuum-time1d在 Ubuntu 20 中使用 systemd 服务运行 Python 程序时systemd 有自己的日志管理机制不会直接生成 nohup.out 文件而是将服务的输出重定向到系统日志中 7. 可能遇到‘permission denied’的问题导致无法生成nohup.out文件也可能生成空的nohup.out文件直到程序遇到错误才会生成out文件然后把错误日志输出
2. 建议直接在service文件中运行python程序不使用nohup另外配置日志输出
使用绝对路径nohup不适合开机启动nohup主要用于在交互式shell中运行命令使其在后台运行并忽略挂起HUP信号。在开机启动脚本中你通常不需要nohup因为这些脚本本身就是在系统启动时以非交互式方式运行的。
service文件内容如下
[Unit]
DescriptionMy Python Program
Afternetwork.target[Service]
Typesimple
ExecStart/usr/bin/python3 -u /path/to/your/python_program.py
WorkingDirectory/path/to/working/directory
StandardOutputfile:/home/to/yourfile.log
StandardErrorfile:/home/to/yourfilerror.log
Useryour_user
Groupyour_group
Restarton-failure
EnvironmentPYTHONPATH/path/to/python/lib[Install]
WantedBymulti-user.target3. 停止删除服务
禁用并停止服务 sudo systemctl stop your_service_name.servicesudo systemctl disable your_service_name.service删除服务文件可选 sudo rm /etc/systemd/system/your_service_name.service
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/918176.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!