让Python脚本在Ubuntu后台运行

学习笔记作者:admin日期:2025-07-25点击:20

摘要:介绍四种方法使Python脚本在Ubuntu关掉终端后仍能在后台持续运行,包括使用nohup、screen、tmux及systemd服务。

让Python脚本在Ubuntu后台运行

要让这个Python脚本在Ubuntu中即使关闭终端也能后台运行,可以采用以下几种常见方法。

方法一:使用nohup命令

最简单的方式是使用nohup命令:

nohup python /www/wwwroot/jishigu.com/aaaa/duanju/3v.py > output.log 2>&1 &

解释:

  • nohup: 不会因终端关闭而终止。
  • output.log: 输出日志保存于此。
  • &: 将任务放到后台。

检查进程:ps aux | grep 3v.py

停止程序:kill PID

方法二:使用screen

安装screen工具:

sudo apt update
sudo apt install screen

启动会话:screen -S mypython

运行脚本:python /www/wwwroot/jishigu.com/aaaa/duanju/3v.py

分离会话:Ctrl + A再按D

恢复会话:screen -r mypython

方法三:使用tmux

安装tmux工具:

sudo apt install tmux

创建会话:tmux new -s mysession

运行脚本:python /www/wwwroot/jishigu.com/aaaa/duanju/3v.py

分离会话:Ctrl + B再按D

恢复会话:tmux attach -t mysession

方法四:使用systemd

创建服务文件:

[Unit]
Description=My Python Script

[Service]
ExecStart=/usr/bin/python3 /www/wwwroot/jishigu.com/aaaa/duanju/3v.py
WorkingDirectory=/www/wwwroot/jishigu.com/aaaa/duanju/
Restart=always
User=your_username

[Install]
WantedBy=multi-user.target

启用并启动服务:

sudo systemctl daemon-reload
sudo systemctl enable my3v
sudo systemctl start my3v

查看状态:sudo systemctl status my3v

总结推荐

方法 是否推荐 说明
nohup ✅ 推荐 简单快速,适合一次性运行
screen/tmux ✅✅ 推荐 可交互调试,适合开发测试
systemd ✅✅✅ 强烈推荐 用于部署生产环境、开机自启等

上一篇      下一篇