当前位置:首页 > Python > 正文

Ubuntu运行Python程序详细教程 - 从安装到执行 | Python编程指南

Ubuntu运行Python程序完整教程

本教程适用于Ubuntu 18.04及以上版本,涵盖Python环境配置、程序编写与执行全流程

一、检查Python环境

Ubuntu系统通常预装Python 3,打开终端(Ctrl+Alt+T)输入:

python3 --version

若显示类似Python 3.8.10的版本信息,说明Python已安装

二、安装Python(可选)

若未安装或需更新版本:

sudo apt update
sudo apt install python3

安装pip包管理工具:

sudo apt install python3-pip

三、编写Python程序

1. 创建.py文件(例如hello.py):

nano hello.py  # 使用nano编辑器

2. 输入示例代码:

#!/usr/bin/env python3
print("Ubuntu Python教程成功运行!")
print(f"当前Python版本: {__import__('sys').version}")

3. 保存文件(Ctrl+O),退出编辑器(Ctrl+X)

四、运行Python程序

方法1:使用Python解释器

python3 hello.py

方法2:直接执行脚本

① 添加执行权限:

chmod +x hello.py

② 运行程序:

./hello.py

💡 成功运行后将显示:

Ubuntu Python教程成功运行!
当前Python版本: 3.8.10 (default, ...)

五、常见问题解决

问题1:Command 'python3' not found
➤ 解决方案:重新安装Python sudo apt install python3

问题2:Permission denied错误
➤ 解决方案:添加执行权限 chmod +x 文件名.py

问题3:No such file or directory
➤ 解决方案:确认文件路径正确,可使用ls查看当前目录文件

六、进阶技巧

1. 虚拟环境使用
python3 -m venv myenv 创建虚拟环境
source myenv/bin/activate 激活环境

2. 定时运行脚本
使用crontab设置定时任务:
crontab -e 添加 * * * * * /usr/bin/python3 /path/to/script.py

现在您已掌握在Ubuntu系统中运行Python程序的核心技能!尝试创建更复杂的程序或探索Python强大的库生态系统吧。

发表评论