温馨提示×

ubuntu python脚本怎么跑

小樊
56
2026-10-07 08:23:59
栏目: 编程语言

在 Ubuntu 上跑 Python 脚本一般有下面几种常见方式,从最基础到稍高级一点:


一、最基础:直接用 python 命令运行

1. 写一个简单的脚本

nano hello.py

内容:

print("Hello Ubuntu")

2. 运行脚本

python3 hello.py

Ubuntu 一般默认是 Python 3,python 可能不存在或指向 Python 2


二、赋予可执行权限(像命令一样运行)

1. 在脚本第一行加 shebang

#!/usr/bin/env python3
print("Hello Ubuntu")

2. 赋予执行权限

chmod +x hello.py

3. 运行

./hello.py

三、使用虚拟环境(推荐)

避免污染系统 Python:

python3 -m venv venv
source venv/bin/activate
pip install requests
python hello.py

退出虚拟环境:

deactivate

四、后台运行(不占用终端)

nohup python3 hello.py > log.txt 2>&1 &

查看进程:

ps aux | grep hello.py

五、定时运行(cron)

编辑定时任务:

crontab -e

例如每天 8 点运行:

0 8 * * * /usr/bin/python3 /home/user/hello.py

六、常见问题

1. python: command not found

用:

python3

2. 没有 pip

sudo apt update
sudo apt install python3-pip

3. 权限不足

sudo python3 hello.py

如果你愿意,可以告诉我:

  • 脚本是干啥的(爬虫 / 服务 / 定时任务)
  • 是否要开机自启
  • 是否是 Flask / Django 项目

我可以给你更具体的运行方式。

0 踩