温馨提示×

centos怎样远程跑python

小樊
40
2026-10-23 21:37:49
栏目: 编程语言

在 CentOS 上“远程跑 Python”通常有几种常见场景,下面按使用方式给你讲清楚,你可以看哪种适合你。


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

1️⃣ 前提

  • CentOS 已安装并开启 SSH
  • 你本地能 SSH 连上 CentOS
ssh user@centos_ip

2️⃣ 直接运行 Python 脚本

python3 test.py

或一行执行:

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

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

方法 1:nohup

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

查看输出:

tail -f out.log

方法 2:screen

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

重新进入:

screen -r

方法 3:tmux(推荐)

tmux
python3 test.py
# Ctrl+B D

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

1️⃣ PyCharm 远程解释器

  • Tools → Deployment
  • 配置 SFTP
  • 设置 Remote Python Interpreter

2️⃣ VS Code + Remote SSH

扩展:Remote - SSH

连接后可像本地一样跑 Python


四、Web 方式远程跑(给其他人用)

Flask / FastAPI

from flask import Flask
app = Flask(__name__)

@app.route("/run")
def run():
    return "hello"

启动:

nohup python3 app.py > app.log 2>&1 &

五、定时远程跑(自动化)

crontab -e

示例(每天 3 点):

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

六、常见问题

Python 不存在?

which python3

安装:

yum install python3

权限问题?

chmod +x test.py

如果你能说清楚:

  • ✅ 是自己用还是别人调用
  • ✅ 是否要长期运行
  • ✅ 是否有Web / API 需求

我可以直接给你一套最合适的方案。

0 踩