pip basic

# 列出当前包列表
pip list

# 查看包详情
pip show requests

# 指定源安装
pip install -i https://test.pypi.org/simple/ rptree

# 也可以在~/.pip/pip.conf中定义源头

[global]
index-url = https://test.pypi.org/simple/

# 可以从github安装
pip install git+https://github.com/realpython/rptree

# 编辑模式安装,适用于调试自己的包
# 会在site-packages目录建立链接,
# 链接到当前项目到路径
python -m pip install -e .

# 生成requirements.txt
pip freeze > requirements.txt

# 安装依赖环境
pip install -r requirements.txt

# 更新依赖环境
pip install -U -r requirements.txt

# 卸载package
pip uninstall urllib3 -y

# 卸载整个依赖
pip uninstall -r requirements.txt -y

requirements

# requirements.txt

certifi==x.y.z
charset-normalizer==x.y.z
idna==x.y.z
requests>=x.y.z, <3.0
urllib3==x.y.z

隔离生产和开发环境

# requirements_dev.txt

-r requirements.txt
pytest>=x.y.z

python包调试并编译发布

主要分成如下步骤

  • 定义pyproject.toml
  • 定义setup.cfg
  • pyproject.toml示例如下
[build-system]
requires = ['setuptools>=42']
build-backend = 'setuptools.build_meta'
[metadata]
name = carlton_template
version = 0.1.0
author = Carlton
author_email = carlton2tang@gmail.com
description = A simple example to understand the basics of developing your first Python package.
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/2niuhe/python_template_carlton
project_urls =
    Bug Tracker = https://github.com/2niuhe/python_template_carlton/issues
    repository = https://github.com/2niuhe/python_template_carlton
classifiers =
    Programming Language :: Python :: 3
    License :: OSI Approved :: MIT License
    Operating System :: OS Independent

[options]
zip_safe = False
include_package_data = True
packages = find:
package_dir =
    = src
python_requires = >=3.6

[options.entry_points]
console_scripts = 
    test-hello = carlton_template.mod:hello

[options.packages.find]
where = src
  • 使用pip安装本地包调试
# 编辑模式安装包
pip install -e .

# 调试正常后生成tar包
pip install -U build
python -m build

# 在dist目录下生成了tar.gz包和whl包
# tar.gz是源码包
# whl是编译的包
# 试着本地安装whl包或者源码包,都可以正常安装使用
pip install python_template-1.0.0-py3-none-any.whl
  • 上传到testpypi

先到testpypi网站注册并申请api token

pip install --upgrade twine
python -m twine upload --repository testpypi dist/*
  • 从testpypi安装
pip install --index-url https://test.pypi.org/simple/ --no-deps <package_name>

测试无问题后可以同样的方式发布到正式的pypi仓库中

参考

Using Python’s pip to Manage Your Projects’ Dependencies – Real Python

How to Create and Upload Your First Python Package to PyPI

How to Publish an Open-Source Python Package to PyPI – Real Python

Command Line Scripts — Python Packaging Tutorial

setuptools详解 - 形同陌路love - 博客园

3. Writing the Setup Configuration File — Python 3.11.8 documentation

entry_points:程序的入口 | 鲁老师

2niuhe/python_template_carlton: a python project template