Linux 系统保持Python会话,不受到shell断开的影响

最近使用脚本的时候,发现断开shell后,再连接,不知道运行的python有没有还再运行或者程序状况。
在Linux系统中,要让Python程序在后台持续运行且不受Shell断开的影响,可以使用以下几种方法。同时,我也会介绍如何查看和管理这些后台进程。


方法1:使用 nohup + &(最简单)

nohup python3 main.py > output.log 2>&1 &
  • nohup:确保进程在终端关闭后仍继续运行。
  • > output.log:将标准输出重定向到文件 output.log
  • 2>&1:将标准错误也重定向到同一文件。
  • &:让进程在后台运行。

查看运行情况:

tail -f output.log  # 实时查看日志
ps aux | grep main.py  # 查看进程ID(PID)

关闭进程:

kill -9 <PID>  # 用实际PID替换<PID>

方法2:使用 screentmux(推荐交互式操作)

(1)安装 screen(如果未安装):

sudo apt install screen  # Debian/Ubuntu
sudo yum install screen  # CentOS/RHEL

(2)创建并进入虚拟终端:

screen -S my_python_session  # 创建一个名为"my_python_session"的会话
python3 main.py              # 在会话中运行程序

(3)退出会话(程序继续运行):

Ctrl + A,然后按 D 键(Detach)。

(4)重新连接会话:

screen -r my_python_session  # 恢复会话

(5)查看所有会话:

screen -ls

方法3:使用 systemd(适合生产环境)

(1)创建服务文件:

sudo vim /etc/systemd/system/my_python_service.service

内容如下(根据实际路径修改):

[Unit]
Description=My Python Service
After=network.target

[Service]
User=your_username
WorkingDirectory=/path/to/your/script
ExecStart=/usr/bin/python3 /path/to/your/script/main.py
Restart=always  # 崩溃后自动重启

[Install]
WantedBy=multi-user.target

(2)启动服务:

sudo systemctl daemon-reload
sudo systemctl start my_python_service
sudo systemctl enable my_python_service  # 开机自启

(3)查看状态和日志:

sudo systemctl status my_python_service
journalctl -u my_python_service -f  # 实时查看日志

方法4:使用 tmux(类似 screen 但更强大)

(1)安装 tmux

sudo apt install tmux  # Debian/Ubuntu
sudo yum install tmux  # CentOS/RHEL

(2)创建会话并运行程序:

tmux new -s my_python_session
python3 main.py

(3)退出会话:

Ctrl + B,然后按 D 键。

(4)重新连接:

tmux attach -t my_python_session

总结:

  • 简单临时任务:用 nohupscreen/tmux
  • 长期生产环境:用 systemd 托管服务。
  • 查看进程ps aux | grep main.pyjournalctl(systemd服务)。
  • 查看输出:直接读日志文件(如 output.log)或通过 screen/tmux 回话。

选择最适合你场景的方式即可!

posted @ 2025-04-14 10:05  旗阳  阅读(21)  评论(0)    收藏  举报