温馨提示×

debian中python如何启

小樊
40
2026-09-17 07:48:39
栏目: 编程语言

在 Debian 中启动 / 使用 Python,通常有以下几种常见方式,取决于你是想交互式运行运行脚本,还是作为服务后台运行


一、确认 Python 是否已安装

python3 --version

如果未安装:

sudo apt update
sudo apt install python3 python3-pip

二、交互式启动 Python

python3

退出:

exit()

或按 Ctrl + D


三、运行 Python 脚本

假设你有 test.py

python3 test.py

如果有可执行权限且脚本头部写了 shebang:

#!/usr/bin/env python3

可这样运行:

chmod +x test.py
./test.py

四、后台运行 Python(常用)

1️⃣ 使用 nohup

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

查看进程:

ps aux | grep python3

2️⃣ 使用 screen

sudo apt install screen
screen -S py
python3 test.py
# Ctrl+A 再按 D 退出

恢复:

screen -r py

五、作为系统服务运行(推荐生产环境)

创建服务文件:

sudo nano /etc/systemd/system/mypy.service

示例内容:

[Unit]
Description=Python Script
After=network.target

[Service]
ExecStart=/usr/bin/python3 /home/user/test.py
WorkingDirectory=/home/user
Restart=always
User=user

[Install]
WantedBy=multi-user.target

启动:

sudo systemctl daemon-reload
sudo systemctl start mypy
sudo systemctl enable mypy

查看状态:

systemctl status mypy

六、虚拟环境(推荐)

python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
python test.py

如果你是指:

  • 开机自启
  • Web 服务(Flask / Django)
  • Docker 中运行
  • 特定版本 Python

可以告诉我你的具体使用场景,我可以给你更精确的方案。

0