在 CentOS 上“远程跑 Python”通常有几种常见场景,下面按使用方式给你系统梳理一下,你可以按需选择。
ssh user@centos_ip "python3 /home/user/test.py"
适合:
ssh user@centos_ip
python3 test.py
nohup python3 test.py > output.log 2>&1 &
查看日志:
tail -f output.log
screen
python3 test.py
# Ctrl+A D 退出
恢复:
screen -r
tmux
python3 test.py
# Ctrl+B D
恢复:
tmux attach
# app.py
from flask import Flask
app = Flask(__name__)
@app.route("/run")
def run():
return "python executed"
运行:
python3 app.py
远程访问:
http://centos_ip:5000/run
crontab -e
示例(每天 2 点):
0 2 * * * /usr/bin/python3 /home/user/test.py
which python3
安装:
yum install python3
chmod +x test.py
| 需求 | 推荐方式 |
|---|---|
| 临时跑脚本 | SSH |
| 长时间任务 | nohup / tmux |
| 开发调试 | VS Code / PyCharm |
| 对外服务 | Flask / FastAPI |
| 定时任务 | crontab |
如果你能说清楚:
我可以给你更精确的方案。