Skip to content

Python 常用基础与打包笔记

1. Python 环境与基础运行

bash
# 查看版本
python --version

# 直接运行
python main.py

# 创建虚拟环境
python -m venv venv

# 激活虚拟环境 (Windows)
call venv\Scripts\activate

# 激活虚拟环境 (Linux/macOS)
source venv/bin/activate

# 退出虚拟环境
deactivate

2. Pip 包管理

bash
# 列出已安装包
pip list

# 显示包信息
pip show pyinstaller

# 安装包
pip install requests

# 升级包
pip install --upgrade requests

# 卸载包
pip uninstall requests

# 换源加速安装(清华源)
pip install requests -i [https://pypi.tuna.tsinghua.edu.cn/simple](https://pypi.tuna.tsinghua.edu.cn/simple)

# 导出当前环境依赖
pip freeze > requirements.txt

# 从依赖文件安装
pip install -r requirements.txt

3. PyInstaller 打包

bash
# 安装
pip install pyinstaller

# 打包为文件夹模式
pyinstaller your_script.py

# 打包为单文件(推荐)
pyinstaller --onefile your_script.py

# 打包并隐藏控制台窗口(适合GUI应用)
pyinstaller --onefile --windowed your_script.py

# 打包并指定图标
pyinstaller --onefile --icon=app.ico your_script.py

# 指定打包后的文件名
pyinstaller --onefile --name=MyTool your_script.py

# 打包前清理缓存
pyinstaller --clean --onefile your_script.py

# 携带外部数据文件打包(Windows环境)
pyinstaller --onefile --add-data "config.json;." your_script.py