在 Ubuntu 下用 Python 写脚本其实很简单,下面从准备环境 → 写脚本 → 运行脚本 → 常见示例一步步说明。
Ubuntu 通常自带 Python 3:
python3 --version
如果没有安装:
sudo apt update
sudo apt install python3
(可选)安装 pip:
sudo apt install python3-pip
nano hello.py
#!/usr/bin/env python3
print("Hello, Ubuntu!")
#!/usr/bin/env python3:指定用 Python3 解释器(推荐)print():Python 3 的输出函数Ctrl + O 保存Ctrl + X 退出python3 hello.py
chmod +x hello.py
./hello.py
import sys
print("参数个数:", len(sys.argv))
print("参数列表:", sys.argv)
运行:
python3 test.py a b c
with open("test.txt", "w") as f:
f.write("Ubuntu Python 脚本示例\n")
读取:
with open("test.txt", "r") as f:
print(f.read())
import os
os.system("ls -l")
或使用更推荐的 subprocess:
import subprocess
subprocess.run(["ls", "-l"])
编辑定时任务:
crontab -e
每天 8 点运行脚本:
0 8 * * * /usr/bin/python3 /home/user/hello.py
nano / vimsudo apt install python3-venv
python3 -m venv venv
source venv/bin/activate
如果你有具体需求(比如:文件处理、网络请求、自动化运维、爬虫、AI 脚本),可以告诉我,我可以给你写完整示例。