Python开发工程师必会的指令
掌握这些开发指令,让你成为高效的Python开发者
欢迎大家关注此公众号,后台点击按钮【免费资料】可免费获取【Python入门30节课】电子书
此外小庄推荐一本适合于新手\小白入手一本 Python基础书籍,欢迎大家订阅,也感谢大家支持,我才有更新的动力
前言
Python开发工程师需要掌握代码质量、测试、调试、版本控制、项目管理等核心技能。本文将系统性地介绍开发工程师必须掌握的指令和工具,帮助你提升开发效率和代码质量。
一、环境管理指令
1.1 Python版本管理
# 查看Python版本
python --version
python -V
# 查看Python路径
which python
where python
# 使用pyenv管理多个Python版本(Linux/Mac)
pyenv install 3.9.0
pyenv install 3.10.0
pyenv global 3.10.0
pyenv local 3.9.0
# 使用conda管理环境
conda create -n myenv python=3.9
conda activate myenv
conda deactivate
conda env list
1.2 虚拟环境管理
# 使用venv
python -m venv myenv
source myenv/bin/activate # Linux/Mac
myenv\Scripts\activate # Windows
deactivate
# 使用virtualenv
pip install virtualenv
virtualenv myenv
source myenv/bin/activate
# 使用pipenv
pip install pipenv
pipenv install
pipenv shell
pipenv install requests
pipenv install --dev pytest
# 使用poetry
pip install poetry
poetry init
poetry add requests
poetry add --dev pytest
poetry shell
poetry install
1.3 依赖管理
# 生成requirements.txt
pip freeze > requirements.txt
# 安装依赖
pip install -r requirements.txt
# 查看已安装的包
pip list
pip list --format=freeze
# 查看包信息
pip show requests
# 升级包
pip install --upgrade requests
# 卸载包
pip uninstall requests
# 检查过时的包
pip list --outdated
二、代码质量指令
2.1 代码格式化
# 使用black格式化
pip install black
black myfile.py
black --line-length 88 myfile.py
black --check myfile.py # 检查但不修改
# 使用autopep8格式化
pip install autopep8
autopep8 --in-place myfile.py
autopep8 --aggressive --in-place myfile.py
# 使用yapf格式化
pip install yapf
yapf --style=google myfile.py
yapf --in-place myfile.py
# 使用isort排序导入
pip install isort
isort myfile.py
isort --check-only myfile.py
isort --diff myfile.py
2.2 代码检查
# 使用pylint检查
pip install pylint
pylint myfile.py
pylint --disable=C0114 myfile.py # 禁用特定警告
# 使用flake8检查
pip install flake8
flake8 myfile.py
flake8 --max-line-length=100 myfile.py
flake8 --ignore=E501 myfile.py # 忽略行长度警告
# 使用mypy类型检查
pip install mypy
mypy myfile.py
mypy --ignore-missing-imports myfile.py
mypy --strict myfile.py
# 使用bandit安全检查
pip install bandit
bandit myfile.py
bandit -r . # 递归检查目录
2.3 代码复杂度分析
# 使用radon计算复杂度
pip install radon
radon cc myfile.py -a # 计算圈复杂度
radon mi myfile.py # 计算可维护性指数
radon raw myfile.py # 计算原始指标
# 使用xenon检查复杂度阈值
pip install xenon
xenon --max-absolute A myfile.py
xenon --max-modules A myfile.py
三、测试指令
3.1 pytest测试框架
# 安装pytest
pip install pytest
# 运行测试
pytest
pytest myfile.py
pytest -v # 详细输出
pytest -x # 遇到第一个失败就停止
pytest -k "test_name"# 运行匹配的测试
pytest -m "slow"# 运行标记的测试
# 生成测试报告
pytest --html=report.html
pytest --cov=. --cov-report=html
# 查看测试覆盖率
pip install pytest-cov
pytest --cov=myproject --cov-report=term-missing
pytest --cov=myproject --cov-report=html
3.2 编写测试用例
import pytest
# 基本测试
deftest_addition():
assert1 + 1 == 2
# 测试异常
deftest_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
# 参数化测试
@pytest.mark.parametrize("input,expected", [
(1, 2),
(2, 4),
(3, 6),
])
deftest_multiply_by_two(input, expected):
assertinput * 2 == expected
# 测试类
classTestCalculator:
deftest_add(self):
assert1 + 1 == 2
deftest_subtract(self):
assert2 - 1 == 1
# fixture
@pytest.fixture
defsample_data():
return {'name': 'Alice', 'age': 25}
deftest_sample_data(sample_data):
assert sample_data['name'] == 'Alice'
# 标记
@pytest.mark.slow
deftest_slow_function():
import time
time.sleep(5)
assertTrue
3.3 Mock测试
from unittest.mock import Mock, patch, MagicMock
import pytest
# Mock对象
deftest_with_mock():
mock_obj = Mock()
mock_obj.method.return_value = 'mocked'
assert mock_obj.method() == 'mocked'
# Patch装饰器
@patch('mymodule.requests.get')
deftest_api_call(mock_get):
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {'key': 'value'}
result = mymodule.fetch_data()
assert result == {'key': 'value'}
# MagicMock
deftest_magic_mock():
mock = MagicMock()
mock.__str__.return_value = 'mocked string'
assertstr(mock) == 'mocked string'
3.4 性能测试
# 使用pytest-benchmark
pip install pytest-benchmark
# 测试代码性能
pytest --benchmark-only
pytest --benchmark-compare
import pytest
deftest_sort_performance(benchmark):
data = [5, 3, 1, 4, 2]
benchmark(lambda: sorted(data))
四、调试指令
4.1 pdb调试器
import pdb
defbuggy_function():
x = 1
pdb.set_trace() # 设置断点
y = x + 1
return y
# 常用pdb命令
# n - 下一行
# s - 进入函数
# c - 继续执行
# p variable - 打印变量
# l - 显示代码
# q - 退出
# h - 帮助
4.2 使用breakpoint()
defmy_function():
x = 10
breakpoint() # Python 3.7+
y = x + 1
return y
4.3 使用icecream调试
pip install icecream
from icecream import ic
defmy_function():
x = 10
y = 20
ic(x, y) # 输出: ic| x: 10, y: 20
result = x + y
ic(result) # 输出: ic| result: 30
return result
4.4 日志调试
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
defmy_function():
logger.debug('调试信息')
logger.info('一般信息')
logger.warning('警告信息')
logger.error('错误信息')
logger.critical('严重错误')
五、版本控制指令
5.1 Git基础指令
# 初始化仓库
git init
# 克隆仓库
git clone https://github.com/user/repo.git
# 查看状态
git status
# 添加文件到暂存区
git add .
git add file.py
# 提交
git commit -m "提交信息"
git commit -am "提交信息"# 添加并提交已跟踪的文件
# 查看提交历史
git log
git log --oneline
git log --graph
git log -p # 显示差异
# 查看差异
git diff
git diff --staged
git diff branch1..branch2
# 撤销修改
git checkout -- file.py # 撤销工作区修改
git reset HEAD file.py # 撤销暂存区修改
git reset --soft HEAD~1 # 撤销提交但保留修改
git reset --hard HEAD~1 # 撤销提交并丢弃修改
5.2 Git分支管理
# 查看分支
git branch
git branch -a
git branch -v
# 创建分支
git branch feature
git checkout -b feature
# 切换分支
git checkout feature
git switch feature
# 合并分支
git merge feature
git merge --no-ff feature # 不使用快进合并
# 删除分支
git branch -d feature
git branch -D feature # 强制删除
# 变基
git rebase main
git rebase --continue
git rebase --abort
5.3 Git远程操作
# 查看远程仓库
git remote -v
# 添加远程仓库
git remote add origin https://github.com/user/repo.git
# 推送到远程
git push origin main
git push -u origin main # 设置上游分支
# 拉取远程更新
git pull origin main
git pull --rebase origin main
# 获取远程更新(不合并)
git fetch origin
# 查看远程分支
git branch -r
5.4 Git高级操作
# 暂存工作区
git stash
git stash list
git stash pop
git stash apply
git stash drop
# Cherry-pick
git cherry-pick commit_hash
# 标签
git tag v1.0.0
git tag -a v1.0.0 -m "版本1.0.0"
git push origin v1.0.0
# 查看提交详情
git show commit_hash
# 搜索
git log --grep="关键词"
git log -S "代码内容"
六、项目管理指令
6.1 项目结构
myproject/
├── src/
│ └── myproject/
│ ├── __init__.py
│ ├── main.py
│ ├── models/
│ ├── services/
│ └── utils/
├── tests/
│ ├── __init__.py
│ ├── test_main.py
│ └── test_models.py
├── docs/
├── .gitignore
├── requirements.txt
├── setup.py
├── pyproject.toml
└── README.md
6.2 setup.py配置
from setuptools import setup, find_packages
setup(
name='myproject',
version='0.1.0',
packages=find_packages(where='src'),
package_dir={'': 'src'},
install_requires=[
'requests>=2.25.0',
'pandas>=1.3.0',
],
extras_require={
'dev': [
'pytest>=6.0',
'black>=21.0',
'flake8>=3.9',
'mypy>=0.900',
],
},
python_requires='>=3.8',
author='Your Name',
author_email='your@email.com',
description='A short description of the package',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
url='https://github.com/user/myproject',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
],
)
6.3 pyproject.toml配置
[build-system]
requires = ["setuptools>=45", "wheel"]
build-backend = "setuptools.backends._legacy:_Backend"
[project]
name = "myproject"
version = "0.1.0"
description = "A short description of the package"
readme = "README.md"
license = {text = "MIT"}
authors = [
{name = "Your Name", email = "your@email.com"},
]
requires-python = ">=3.8"
dependencies = [
"requests>=2.25.0",
"pandas>=1.3.0",
]
[project.optional-dependencies]
dev = [
"pytest>=6.0",
"black>=21.0",
"flake8>=3.9",
"mypy>=0.900",
]
[tool.black]
line-length = 88
target-version = ['py38']
[tool.isort]
profile = "black"
line_length = 88
[tool.mypy]
python_version = "3.8"
warn_return_any = true
warn_unused_configs = true
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
python_functions = ["test_*"]
七、文档生成指令
7.1 Sphinx文档
# 安装Sphinx
pip install sphinx
# 初始化文档
sphinx-quickstart docs
# 构建文档
cd docs
make html
make latexpdf
# 使用ReadTheDocs主题
pip install sphinx-rtd-theme
7.2 docstring规范
defcalculate_sum(a: int, b: int) -> int:
"""
计算两个整数的和。
Args:
a (int): 第一个整数
b (int): 第二个整数
Returns:
int: 两个整数的和
Raises:
TypeError: 如果参数不是整数
Examples:
>>> calculate_sum(1, 2)
3
>>> calculate_sum(-1, 1)
0
"""
ifnotisinstance(a, int) ornotisinstance(b, int):
raise TypeError("参数必须是整数")
return a + b
7.3 mkdocs文档
# 安装mkdocs
pip install mkdocs
# 创建项目
mkdocs new my-project
# 启动开发服务器
mkdocs serve
# 构建文档
mkdocs build
# 部署到GitHub Pages
mkdocs gh-deploy
八、性能分析指令
8.1 cProfile性能分析
import cProfile
import pstats
defmy_function():
total = 0
for i inrange(1000000):
total += i
return total
# 使用cProfile
cProfile.run('my_function()', 'output.prof')
# 分析结果
p = pstats.Stats('output.prof')
p.sort_stats('cumulative').print_stats(10)
p.print_callers('my_function')
8.2 line_profiler逐行分析
pip install line_profiler
@profile
defmy_function():
total = 0
for i inrange(1000000):
total += i
return total
kernprof -l -v myfile.py
8.3 memory_profiler内存分析
pip install memory_profiler
@profile
defmy_function():
a = [i for i inrange(100000)]
b = [i * 2for i in a]
return b
python -m memory_profiler myfile.py
8.4 timeit时间测量
import timeit
# 测量代码执行时间
execution_time = timeit.timeit('sum(range(1000))', number=10000)
print(f'执行时间: {execution_time}秒')
# 测量函数执行时间
defmy_function():
returnsum(range(1000))
execution_time = timeit.timeit(my_function, number=10000)
print(f'执行时间: {execution_time}秒')
九、打包与发布指令
9.1 打包Python项目
# 安装打包工具
pip install setuptools wheel
# 构建分发包
python setup.py sdist bdist_wheel
# 使用build工具
pip install build
python -m build
# 生成的文件
# dist/
# ├── myproject-0.1.0.tar.gz
# └── myproject-0.1.0-py3-none-any.whl
9.2 发布到PyPI
# 安装twine
pip install twine
# 上传到TestPyPI
twine upload --repository testpypi dist/*
# 上传到PyPI
twine upload dist/*
# 检查分发包
twine check dist/*
9.3 使用PyInstaller打包
# 安装PyInstaller
pip install pyinstaller
# 打包为单个可执行文件
pyinstaller --onefile myscript.py
# 打包为目录
pyinstaller myscript.py
# 带图标打包
pyinstaller --onefile --icon=app.ico myscript.py
# 打包为窗口应用(无控制台)
pyinstaller --onefile --windowed myscript.py
十、CI/CD指令
10.1 GitHub Actions
# .github/workflows/python-app.yml
name:Pythonapplication
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on:ubuntu-latest
steps:
-uses:actions/checkout@v2
-name:SetupPython
uses:actions/setup-python@v2
with:
python-version:'3.9'
-name:Installdependencies
run:|
python -m pip install --upgrade pip
pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
-name:Lintwithflake8
run:|
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
-name:Testwithpytest
run:|
pytest
10.2 GitLab CI
# .gitlab-ci.yml
image:python:3.9
stages:
-test
-lint
-deploy
test:
stage:test
script:
-pipinstall-rrequirements.txt
-pytest
artifacts:
reports:
junit:report.xml
lint:
stage:lint
script:
-pipinstallflake8
-flake8.
deploy:
stage:deploy
script:
-echo"Deploying..."
only:
-main
总结
作为Python开发工程师,掌握这些指令是核心技能:
- 8. 性能分析 - cProfile、line_profiler
- 9. 打包发布 - PyInstaller、PyPI
- 10. CI/CD - GitHub Actions、GitLab CI
掌握这些工具,你就能成为高效的Python开发者。
关注我,获取更多Python技术干货!