Python开发环境设置
流行的Python开发环境为VSCode和PyCharm。本文首先介绍Python相关的环境安装的流程,然后是相关开发工具和插件的设置方法。
系统环境配置
注意 :请不要直接使用apt-get来安装Python,因为linux系统有很多工具依赖python,操作不当可能影响到系统稳定性。
- 推荐使用pyenv来安装Python解释器,它可以同时安装多个版本的python,并支持基于用户/路径来设置python版本。由于Python 2.x 已经全面停止维护,所以在新项目中请使用Python 3.5+ 版本。对于Python而言,第二位版本号的增加通常会引入新的特性(例如新的语法,新的解释器实现等)。因此,使用了新版本特性的Python代码通常是不能够在低版本的Python上运行的;但新版本的Python解释器向下兼容语法特性(例如Python3.10解释器向下兼容Python3引入的所有语法特性)。此外,新版本的Python解释器由于实现的优化,通常具有更快的运行速度。因此,对于新项目而言,请尽量使用较高版本的Python解释器,除非有特殊的第三方依赖需要特定版本的Python。但需要注意的是,但对于高版本的Python,使用新特性时请考虑到可能的向下兼容的需求。
pyenv安装和使用
链接:pyenv/pyenv: Simple Python version management
安装
把pyenv的仓库clone到指定目录,然后添加相关的环境变量到/.bashrc或者/.zshrc即可:
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo ‘export PYENV_ROOT=~/.pyenv’ >> ~/.bashrc &&
echo ‘export PATH=
P
Y
E
N
V
R
O
O
T
/
b
i
n
:
PYENV_ROOT/bin:
PYENVROOT/bin:PATH’ >> ~/.bashrc &&
echo ‘eval “KaTeX parse error: Expected 'EOF', got '&' at position 36: …' >> ~/.bashrc &̲& \ echo 'eval …(pyenv init -)”’ >> ~/.bashrc
or for zsh
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo ‘export PYENV_ROOT=~/.pyenv’ >> ~/.zshrc &&
echo ‘export PATH=
P
Y
E
N
V
R
O
O
T
/
b
i
n
:
PYENV_ROOT/bin:
PYENVROOT/bin:PATH’ >> ~/.zshrc &&
echo ‘eval “KaTeX parse error: Expected 'EOF', got '&' at position 35: …"' >> ~/.zshrc &̲& \ echo 'eval …(pyenv init -)”’ >> ~/.zshrc
使用pyenv安装python时,它会在目标平台上编译python,因此需要安装编译python相关的依赖。在ubuntu上使用如下命令安装:
sudo apt-get update
sudo apt-get install make build-essential libssl-dev zlib1g-dev
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
其他的系统安装依赖可以查阅:https://github.com/pyenv/pyenv/wiki#suggested-build-environment
激活环境
source ~/.bashrc
for zsh
source ~/.zshrc
使用
下面列举了常用的命令,更多支持的命令可以查看官方文档
安装指定版本的Python
pyenv install 3.9.6
查看已安装的python版本
pyenv versions
设置全局的Python版本
pyenv global 3.9.6
在某个目录下设置此目录要使用的python版本
pyenv local 3.9.6
poetry安装和使用
链接:Poetry - Python dependency management and packaging made easy
安装
使用如下命令安装,注意安装前需要有一个可以执行的Python解释器。
curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python -
curl -sSL https://install.python-poetry.org | python3 -
使用
与conda不同,poetry是项目的依赖管理工具,它通过pyproject.toml来进行配置。使用如下命令新建一个python项目,poetry会自动添加pyproject.toml。
poetry new poetry-demo
如果要指定Python版本,可以在新建项目之前使用pyenv来设置python版本。
新建的项目目录结构如下:
poetry-demo
├── pyproject.toml
├── README.rst
├── poetry_demo
│ └── init.py
└── tests
├── init.py
└── test_poetry_demo.py
其中pyproject.toml的内容为:
[tool.poetry]
name = “poetry-demo”
version = “0.1.0”
description = “”
authors = [“”]
[tool.poetry.dependencies]
python = “*”
[tool.poetry.dev-dependencies]
pytest = “^3.4”
处理依赖相关的命令为:
添加依赖
poetry add some-package
移除依赖
poetry remove some-package
生成lock文件
poetry lock
在新的环境中安装项目相关的所有依赖(项目包含pyproject.toml)可以使用
poetry install
来安装所有相关依赖。
公司内部pypi仓库
-
发布包相关查阅:Pypi用户使用
-
公司内部仓库通过统一的url进行索引:
https://pkgs.d.xiaomi.net/artifactory/api/pypi/pypi-virtual/simple -
在poetry项目中,可以在pyproject.toml中添加:
[[tool.poetry.source]]
name = “mi-pypi”
url = “https://pkgs.d.xiaomi.net/artifactory/api/pypi/pypi-virtual/simple”
secondary = true
之后就可以通过poetry add来添加相关的依赖,poetry会自动根据不同source进行解析。
项目开发管理通用流程-port
推荐使用poetry进行项目开发管理。
poetry配置
可以选择将poetry生成的虚拟环境配置在project目录下,使用如下命令进行配置:
poetry config virtualenvs.in-project true
新建项目
-
新建项目时,首先使用pyenv安装选用的Python版本并切换至指定版本。
pyenv install 3.8.11
pyenv local 3.8.11 -
使用poetry新建项目:
poetry new my-project -
进入到my-project目录,添加linter,formatter等开发依赖:
poetry add --dev mypy isort yapf==0.31.0 -
在pyproject.toml里添加isort和yapf的配置:
[tool.isort]
force_single_line = true
single_line_exclusions = “typing”
[tool.yapf]
column_limit = 120
-
添加项目需要的依赖,例如fds的sdk:
poetry add galaxy-fds-sdk -
进行完上述操作后,你的pyproject.toml的内容应该是:
[tool.poetry]
name = “my-project”
version = “0.1.0”
description = “”
authors = [“xxx xxx@xiaomi.com”]
[tool.poetry.dependencies]
python = “^3.8”
galaxy-fds-sdk = “^1.4.38”
[tool.poetry.dev-dependencies]
pytest = “^5.2”
mypy = “^0.910”
yapf = “0.31.0”
isort = “^5.9.3”
[build-system]
requires = [“poetry-core>=1.0.0”]
build-backend = “poetry.core.masonry.api”
考虑到兼容多版本Python,[tool.poetry.dependencies]里的python字段可以更改为:
[tool.poetry.dependencies]
python = “>=3.7, <=3.10”
- 稳定依赖后生成lock文件,并push到git仓库:
poetry lock
已有项目
已有项目中的pyproject.toml和poetry.lock已经存在,只需要:
poetry install
即可安装所有相关依赖,并创建相关的虚拟环境(路径在当前目录下的.venv)。
gitignore设置
Python项目会生成非常多的本地文件,使用如下.gitignore
Byte-compiled / optimized / DLL files
pycache/
*.py[cod]
*$py.class
C extensions
*.so
Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
PyInstaller
Usually these files are written by a python script from a template
before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
Installer logs
pip-log.txt
pip-delete-this-directory.txt
Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
Translations
*.mo
*.pot
Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
Flask stuff:
instance/
.webassets-cache
Scrapy stuff:
.scrapy
Sphinx documentation
docs/_build/
PyBuilder
target/
Jupyter Notebook
.ipynb_checkpoints
IPython
profile_default/
ipython_config.py
pyenv
.python-version
pipenv
According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
However, in case of collaboration, if having platform-specific dependencies or dependencies
having no cross-platform support, pipenv may install dependencies that don’t work, or not
install all needed dependencies.
#Pipfile.lock
PEP 582; used by e.g. github.com/David-OConnor/pyflow
pypackages/
Celery stuff
celerybeat-schedule
celerybeat.pid
SageMath parsed files
*.sage.py
Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
Spyder project settings
.spyderproject
.spyproject
Rope project settings
.ropeproject
mkdocs documentation
/site
mypy
.mypy_cache/
.dmypy.json
dmypy.json
Pyre type checker
.pyre/
vscode
.vscode
.devcontainer
VSCode设置
插件和环境配置
完成上述操作后,可以在vscode里配置相关插件进行开发。
- 保证如下插件已经安装:
- Pylance
- Python
-
选择Python解释器:
-
打开一个.py文件,点击左下角:
注:没找到可以用第二种方式,如下图。 参考:https://code.visualstudio.com/docs/python/environments
-
选择本路径下的虚拟环境:
-
设置formatter和linter
-
打开用户配置json:
1. 按F1即可调出快速指令,输入open settings(json)
2. 选择对应选项即可打开用户配置 -
在配置json里添加如下字段:
{
…,
“[python]”: {
“editor.defaultFormatter”: “ms-python.python”
},
“python.formatting.provider”: “yapf”,
“python.languageServer”: “Pylance”,
“python.linting.enabled”: true,
“python.linting.mypyEnabled”: true,
…
} -
设置docstring
-
安装相关插件:njpwerner.autodocstring
-
在希望生成docstring的函数or类的声明下面输入"""并回车即可自动生成docstring。
-
根据eng-practice的规定进行header设置:
注意,也可以使用mikey.vscode-fileheader插件完成此功能。 -
按F1输入user snippets,选择python.json
-
在文件内添加如下字段:
{
“XIAOMI_HEADER”: {
“prefix”: “xiaomi”,
“body”: [
“# =============================================================================”,
“# Copyright © $CURRENT_YEAR Xiaomi EV Company Limited. All rights reserved.”,
“#”,
“# XIAOMI CONFIDENTIAL”,
“#”,
“# Xiaomi EV Company Limited retains all intellectual property and proprietary”,
“# rights in and to this software and related documentation and any”,
“# modifications thereto (“Software”). Any reproduction, disclosure or”,
“# distribution of this Software is strictly prohibited.”,
“#”,
“# Permitted Users may only access, use or edit the Software based on their work”,
“# duties. Permitted Users shall refer to the current employees in Xiaomi EV”,
“# Autonomous Driving Group who have entered into Non-disclosure Agreement with”,
“# Xiaomi, and have been duly authorized to access to the Software.”,
“# =============================================================================”,
]
},
} -
在编辑的Python文件里输入xiaomi即可快速插入header
使用vscode进行格式化和import排序
完成上述配置后,可以在编辑器里点击鼠标右键,选择:
- format document
- sort imports
即可进行自动的代码风格格式化。你也可以使用可自定义的快捷键进行。
使用vscode debug python代码
- 在编辑器点击行号前即可打断点,点击F5即可进行调试。
- 如果需要自定义调试时传入的参数和环境配置,可以点击Add Configuration添加新的调试配置
例如:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
“version”: “0.2.0”,
“configurations”: [
{
“name”: “Python: Current File”,
“type”: “python”,
“request”: “launch”,
“program”: “${file}”,
“console”: “integratedTerminal”,
“args”: [“–set-log”, “–data-path”, “~/data/”],
“env”: {
“MY_ENV_NAME”: “SOME_ENV”
}
}
]
}
详细的配置可以查阅:https://code.visualstudio.com/docs/python/debugging
PyCharm 设置
插件和环境配置
完成上述pyenv 和poetry 的配置后,即可以在PyCharm 中进行配置,Ctrl + Alt + S 打开Settings page,进入File - Settings - Plugins - Marketplace,即可搜索并安装插件
- 推荐安装如下插件
-
.ignore:自动生成gitignore 及其他ignore 文件,安装后可新建文件时选择对应ignore 文件
-
Makefile Language:支持makefile 文件语法高亮
-
Protocol Buffers:提供PB 文件语法支持
-
Requirements:提供requirements.txt 文件相关支持
-
(… … more)
- 设置Python 解释器
-
File - setting - Project: xxx - Python Interpreter,选择/ 添加Python 解释器
-
创建虚拟环境:以采用pyenv + poetry 构建的项目为例,之前的流程中流程中poetry install(poetry update)生成.venv 文件夹后,选择Poetry Environment,Existing environment 中会自动加载venv 文件夹下的/bin/python,点击ok 添加后选择即可
- ubuntu18.04 下PyCharm 中文输入的小BUG 解决
- 安装Fcitx - 安装搜狗输入法 - 卸载ibus
- PyCharm 的Help - Edit Custom VM Options
使用PyCharm 进行格式化和import 排序
使用PyCharm debug python代码