温馨提示×

centos如何远程跑python

小樊
35
2026-09-24 13:55:21
栏目: 编程语言

在 CentOS 上“远程跑 Python”通常有几种常见场景,下面按使用方式给你系统梳理一下,你可以按需选择。


一、SSH 远程执行 Python(最常用)

1️⃣ 直接通过 SSH 运行

ssh user@centos_ip "python3 /home/user/test.py"

适合:

  • 一次性任务
  • 脚本已经在服务器上

2️⃣ 登录后运行

ssh user@centos_ip
python3 test.py

二、后台远程运行 Python(不中断)

✅ nohup(最简单)

nohup python3 test.py > output.log 2>&1 &

查看日志:

tail -f output.log

✅ screen(可恢复会话)

screen
python3 test.py
# Ctrl+A D 退出

恢复:

screen -r

✅ tmux(推荐)

tmux
python3 test.py
# Ctrl+B D

恢复:

tmux attach

三、本地写代码,远程运行(开发方式)

1️⃣ PyCharm 远程解释器

  • Tools → Deployment
  • 配置 SFTP
  • 使用远程 Python 解释器

2️⃣ VS Code Remote - SSH

  • 安装 Remote - SSH
  • 连接 CentOS
  • 直接在服务器上跑 Python

四、Web / API 方式远程调用 Python

Flask / FastAPI

# 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

五、定时远程跑 Python

crontab

crontab -e

示例(每天 2 点):

0 2 * * * /usr/bin/python3 /home/user/test.py

六、常见问题

Python 不存在?

which python3

安装:

yum install python3

权限问题?

chmod +x test.py

总结选型建议

需求 推荐方式
临时跑脚本 SSH
长时间任务 nohup / tmux
开发调试 VS Code / PyCharm
对外服务 Flask / FastAPI
定时任务 crontab

如果你能说清楚:

  • 是本地控制远程,还是别人调用你
  • 是否要常驻
  • 是否要图形界面

我可以给你更精确的方案。

0 踩