
Python 开发指引
环境配置
Linux
# 添加不同版本的 Python 解释器
sudo add-apt-repository ppa:deadsnakes/ppa
国内镜像
/etc/pip.conf 添加一下内容
[global]
index-url=https://mirrors.163.com/pypi/simple
trusted-host=mirrors.163.com
macOS
brew install python # 默认已经开始安装 Python3
brew install ctags
venv
# 当前项目配置 venv
python3 -m venv .venv
# 命令行激活 venv 环境
source .venv/bin/activate
deactivate # 离开 venv 环境
# 升级默认包
pip install --upgrade pip
# 安装常用包
pip install jupyter
pyenv
brew install pyenv
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.zshrc
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/. bash_profile
# 升级
brew update && brew upgrade pyenv
pyenv install 3.7.9
pyenv global 3.7.9
virtualenv
# 安装 virtualenv
# macOS 安装文件夹 ~/Library/Python/3.11/bin
python3.11 -m pip install --user virtualenv
# 激活 virtualenv 环境
source venv/bin/activate
.env
环境变量文件,分离代码与测试用例。
PYTHONPATH=src
docker
PyCharm
第三方库管理
常用命令
常用路径
VS Code
启动 Code 后,安装微软发行的 Python 插件。按 Cmd + Shift + p,输入 Select Interpreter,选择 Python 解释器。
"launch": {
"version": "0.2.0",
"configurations": [
{
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/manage.py",
"args": ["runserver"],
"django": true,
"justMyCode": true
},
{
"name": "Python: File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}
pytest
测试框架,文件名和函数需要 test_ 开头。
import pytest
@pytest.fixture
assert 条件表达式
pytest.ini
配置 python 代码路径,放置项目根目录。test 目录的测试用例可以访问到项目代码。
[pytest]
pythonpath = src
运行
# 运行测试用例
pytest # 测试所有用例
python3 -m pytest
pytest 文件夹或文件路径 # 测试指定位置的用例
launch.json
{
"name": "pytest: File",
"type": "python",
"request": "launch",
"module": "pytest",
"console": "integratedTerminal",
"cwd": "${workspaceRoot}",
"args": [
"${file}"
],
"justMyCode": true
},
{
"name": "pytest: All",
"type": "python",
"request": "launch",
"module": "pytest",
"console": "integratedTerminal",
"cwd": "${workspaceRoot}",
"args": [
"test"
],
"justMyCode": true
}
IDLE
交互式运行
Windows 命令行输入 IDLE 启动交互式命令行 Python Shell。
编辑代码
IDLE 有自己的菜单,选择 File > New File,可新建文件编辑代码:
# Receive input then store in name variable.
name = input("What's your name?\n")
print("Hi,", name)
按 F5 或菜单栏 Run > Run Module,运行当前文件: