Linux上Python脚本后台运行指南
在 Linux 系统中,可以通过多种方式让 Python 脚本在后台运行,以下是几种常见的方法:
方法 1:使用 & 符号(后台运行)
直接在命令末尾加上 &,让脚本在后台运行:
python3 your_script.py &
如何关闭后台任务
- 查看后台任务:
jobs -l - 终止任务:
kill %1 # 1 是任务编号
方法 2:使用 nohup(终端关闭后仍运行)
nohup(no hang up)可以让脚本在终端关闭后继续运行:
nohup python3 your_script.py > output.log 2>&1 &
> output.log:将标准输出重定向到 output.log。2>&1:将标准错误(stderr)也重定向到 output.log。&:后台运行。如何停止 nohup 任务
- 查找进程 ID(PID):
ps aux | grep "your_script.py" - 终止进程:
kill -9 <PID>
方法 3:使用 screen 或 tmux(会话管理)
screen 方式
- 创建新会话:
screen -S python_session - 运行脚本:
python3 your_script.py - 按
Ctrl + A,然后D脱离会话(detach)。 - 重新进入会话:
screen -r python_session - 关闭会话:
exit
tmux 方式(推荐)
- 创建新会话:
tmux new -s python_session - 运行脚本:
python3 your_script.py - 按
Ctrl + B,然后D脱离会话。 - 重新进入会话:
tmux attach -t python_session - 关闭会话:
exit
方法 4:使用 systemd(系统服务,长期运行)
适用于需要长期运行的后台服务:
- 创建服务文件:
sudo nano /etc/systemd/system/python_script.service - 写入以下内容:
[Unit] Description=Python Script Service After=network.target [Service] User=your_username ExecStart=/usr/bin/python3 /path/to/your_script.py Restart=always [Install] WantedBy=multi-user.target - 启用并启动服务:
sudo systemctl daemon-reload sudo systemctl enable python_script sudo systemctl start python_script - 查看状态:
sudo systemctl status python_script - 停止服务:
sudo systemctl stop python_script
总结
| 方法 | 适用场景 | 终端关闭后是否运行 | 推荐指数 |
|---|---|---|---|
& |
临时后台 | ❌ 会终止 | ⭐⭐ |
nohup |
长期运行 | ✅ 继续运行 | ⭐⭐⭐ |
screen/tmux |
会话管理 | ✅ 继续运行 | ⭐⭐⭐⭐ |
systemd |
系统服务 | ✅ 长期运行 | ⭐⭐⭐⭐⭐ |
推荐选择:
& 或 nohuptmux/screensystemd在使用 nohup 运行 Python 脚本后,可以通过以下几种方式查看其进程 ID(PID),并进行管理:
1. 直接查看 nohup 输出
运行 nohup 时,它会显示进程 ID(PID):
nohup python3 your_script.py > output.log 2>&1 &
输出示例:
[1] 12345 # 12345 就是 PID
[1] 是作业编号(job ID),12345 是进程 ID(PID)。2. 使用 jobs 查看(仅当前终端有效)
如果仍在同一个终端,可以查看后台任务:
jobs -l
输出示例:
[1]+ 12345 Running nohup python3 your_script.py > output.log 2>&1 &
12345 是 PID,[1] 是作业编号。⚠️ 注意:如果关闭终端或新开终端,
jobs将无法显示。
3. 使用 ps 或 pgrep 查找进程
方法 1:ps aux | grep
ps aux | grep "your_script.py"
输出示例:
your_user 12345 0.0 0.1 12345 6789 pts/0 S 10:00 0:00 python3 your_script.py
12345 就是 PID。方法 2:pgrep(更简洁)
pgrep -f "your_script.py"
直接返回 PID:
12345
4. 查看 nohup.out 或日志文件
如果 nohup 输出到文件(如 nohup.out 或自定义日志),可以检查是否有进程信息:
tail -f nohup.out # 实时查看日志
5. 使用 lsof 查看相关进程
lsof | grep "your_script.py"
输出示例:
python3 12345 your_user cwd DIR /path/to/script
12345 是 PID。如何终止 nohup 进程?
找到 PID 后,用 kill 终止:
kill -9 12345 # 强制终止
或优雅终止:
kill 12345 # 发送 SIGTERM
总结
| 方法 | 命令示例 | 适用场景 |
|---|---|---|
直接查看 nohup 输出 |
nohup python3 script.py & |
刚运行时显示 PID |
jobs -l |
jobs -l |
当前终端有效 |
ps aux | grep |
ps aux | grep "your_script.py" |
通用方法,推荐 |
pgrep -f |
pgrep -f "your_script.py" |
快速获取 PID |
lsof |
lsof | grep "your_script.py" |
查看文件关联的进程 |
推荐使用 ps aux | grep 或 pgrep -f,适用于所有情况!🚀
作者:@昵称不存在