在 Ubuntu 上跑 Python 脚本一般有下面几种常见方式,从最基础到稍高级一点:
nano hello.py
内容:
print("Hello Ubuntu")
python3 hello.py
Ubuntu 一般默认是 Python 3,
python可能不存在或指向 Python 2
#!/usr/bin/env python3
print("Hello Ubuntu")
chmod +x hello.py
./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
编辑定时任务:
crontab -e
例如每天 8 点运行:
0 8 * * * /usr/bin/python3 /home/user/hello.py
python: command not found用:
python3
sudo apt update
sudo apt install python3-pip
sudo python3 hello.py
如果你愿意,可以告诉我:
我可以给你更具体的运行方式。