Skip to content

Python

Python 是荷兰程序员 Guido van Rossum ,用 C 语言实现的支持动态类型、垃圾回收、多种编程范型的高级编程语言, 它跨平台又简单易学,被广泛应用于各个领域,首个公开版本 0.9.0 于 1991 年发布。

安装软件

Windows 系统上安装 Python 解释器

  • 方式 a 通过 Chocolate 安装 choco install python312 --params "/InstallDir:C:\Python312" --force -y ;
  • 方式 b 通过 Microsoft Store 安装 Python 3.x ;

Ubuntu 系统上安装 Python 解释器 apt install python-is-python3

macOS 系统上安装 Python 解释器

shell
brew install python3
brew install pipx

#
echo 'export PATH=$HOME/.local/bin:$PATH' >> ~/.zshrc
# or
echo 'export PATH=$HOME/.local/bin:$PATH' >> ~/.bashrc

pipx install xxx

常见配置

更新项目 requirements.txt 文件 pip freeze > requirements.txt

设置 pip 软件仓库镜像源

设置使用软件仓库使用清华镜像源以加速安装第三方软件包

pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

添加 pip 安装包到环境变量 PATH

Windows 上通过 Microsoft Store 安装 Python 解释器,默认使用 pip 安装包目录不在 PATH,无法直接在终端中使用,需要手动添加。 将以下路径加入到 PATH 环境变量:

%USERPROFILE%\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_abcdefghijklm\LocalCache\local-packages\Python310\Scripts

Windows 上通过 Chocolatey 安装 Python 解释器,默认使用 pip 安装包目录不在 PATH。 解决方法:将以下路径加入到 PATH 环境变量: %USERPROFILE%\AppData\Roaming\Python\Python312\Scripts

并且加 --user 参数安装包到单用户,如: pip install --user pgcli "psycopg[binary,pool]"

安装指定 Github 模块

pip install git+https://github.com/google/yapf.git#egg=yapf

VSCode 使用 yapf 格式化代码

添加配置文件 .style.yapf

[style]
based_on_style = google
spaces_before_comment = 2
split_before_logical_operator = true
disable_split_list_with_comment = true

命令行用法 yapf --style .style.yapf t.py

使用 dotenv

以 Django 为例使用 dotenvx - a better dotenv–from the creator of dotenv.

shell
dotenvx run -f scripts\develop\envs.env -- python manage.py shell
dotenvx run -f scripts\develop\envs.env -- python .tmp.py

常见问题

Error ModuleNotFoundError: No module named 'distutils'

distutils package is removed in python version 3.12

solution: pip install setuptools

常用模块

MySQL driver

PostgreSQL driver

python
import psycopg
from psycopg.rows import dict_row

dsn = 'host=localhost user=postgres password=secret dbname=postgres port=5432 sslmode=disable'
conn = psycopg.connect(dsn, row_factory=dict_row)

with conn.cursor() as cur:
  cur.execute("select * from tbl where id = %s", (123,))
  rows = cur.fetchall()
  print(rows)

Released under the CC-BY-NC-4.0