【PDM教程】3.常见用法

PDM的功能非常强大,通过pdm -h能查看所有支持的命令。但是常用的不多,以下将列举并说明它的常见命令。

pdm -h
Usage: pdm [-h] [-V] [-c CONFIG] [-v | -q] [-I] [--pep582 [SHELL]] ...

    ____  ____  __  ___
   / __ \/ __ \/  |/  /
  / /_/ / / / / /|_/ /
 / ____/ /_/ / /  / /
/_/   /_____/_/  /_/

Options:
  -h, --help            Show this help message and exit.
  -V, --version         Show the version and exit
  -c CONFIG, --config CONFIG
                        Specify another config file path [env var: PDM_CONFIG_FILE]
  -v, --verbose         Use `-v` for detailed output and `-vv` for more detailed
  -q, --quiet           Suppress output
  -I, --ignore-python   Ignore the Python path saved in .pdm-python. [env var: PDM_IGNORE_SAVED_PYTHON]
  --pep582 [SHELL]      Print the command line to be eval'd by the shell

Commands:
  add                   Add package(s) to pyproject.toml and install them
  build                 Build artifacts for distribution
  cache                 Control the caches of PDM
  completion            Generate completion scripts for the given shell
  config                Display the current configuration
  export                Export the locked packages set to other formats
  fix                   Fix the project problems according to the latest version of PDM
  import                Import project metadata from other formats
  info                  Show the project information
  init                  Initialize a pyproject.toml for PDM
  install               Install dependencies from lock file
  list                  List packages installed in the current working set
  lock                  Resolve and lock dependencies
  publish               Build and publish the project to PyPI
  remove                Remove packages from pyproject.toml
  run                   Run commands or scripts with local packages loaded
  search                Search for PyPI packages
  self (plugin)         Manage the PDM program itself (previously known as plugin)
  show                  Show the package information
  sync                  Synchronize the current working set with lock file
  update                Update package(s) in pyproject.toml
  use                   Use the given python version or path as base interpreter
  venv                  Virtualenv management

配置pypi源

通过pdm config能够修改诸多配置,它们以Key-Value的形式进行查看和修改。

# 修改源为中科大的pypi源
pdm config pypi.url http://mirrors.ustc.edu.cn/pypi/web/simple
pdm config pypi.verify_ssl False

它们与以下3种配置方式等价

# 使用pip config命令修改全局pypi源
$ pip config --user set global.index-url http://mirrors.ustc.edu.cn/pypi/web/simple
$ pip config --user set global.trusted-host mirrors.ustc.edu.cn

# 使用pip.conf配置文件修改全局pypi源
$ cat ~/.pip/pip.conf
[global]
index-url = http://mirrors.ustc.edu.cn/pypi/web/simple
trusted-host = mirrors.ustc.edu.cn

# 使用requirements.txt设置当前pypi源
$ cat requirements.txt
-i http://mirrors.ustc.edu.cn/pypi/web/simple --trusted-host mirrors.ustc.edu.cn
requests>=2.31.0

增加依赖库

使用pdm add命令能为当前目录的项目添加依赖库,如pdm add requests

Adding packages to default dependencies: requests
🔒 Lock successful
Changes are written to pyproject.toml.
Synchronizing working set with resolved packages: 10 to add, 0 to update, 0 to remove

  ✔ Install certifi 2023.11.17 successful
  ✔ Install idna 3.6 successful
  ✔ Install deprecation 2.1.0 successful
  ✔ Install packaging 23.2 successful
  ✔ Install urllib3 2.1.0 successful
  ✔ Install charset-normalizer 3.3.2 successful
  ✔ Install requests 2.31.0 successful
  ✔ Install lxml 4.9.3 successful
  ✔ Install pillow 10.1.0 successful
/Users/xx/software/Python-3.11.4/lib/python3.11/site-packages/pdm/models/candidates.py:613: ExtrasWarning: Extras not found for setuptools-scm:
[toml]
  return filter_requirements_with_extras(
  ✔ Install pikepdf 7.2.0 successful

🎉 All complete!

依赖库分组

pdm为依赖库的管理提供了分组能力,常见的组有dev(开发专属)、prod(生产专属)等等,也可以自定义创建组。

# 添加pytest依赖,到dev环境,并加入分组test
pdm add pytest -dG test

查看依赖库

使用pdm list列出当前环境Interpreter已安装的包

pdm list 以表格列出依赖

$ pdm list
╭────────────────────┬────────────┬──────────╮
│ name               │ version    │ location │
├────────────────────┼────────────┼──────────┤
│ pikepdf            │ 8.7.1      │          │
│ lxml               │ 4.9.3      │          │
│ packaging          │ 23.2       │          │
│ requests           │ 2.31.0     │          │
│ urllib3            │ 2.1.0      │          │
│ charset-normalizer │ 3.3.2      │          │
│ certifi            │ 2023.11.17 │          │
│ Deprecated         │ 1.2.14     │          │
│ idna               │ 3.6        │          │
│ Pillow             │ 10.1.0     │          │
│ wrapt              │ 1.16.0     │          │
╰────────────────────┴────────────┴──────────╯

pdm list --tree以树状列出依赖层级

--tree--graph是同一个效果

$ pdm list --tree
pikepdf 8.7.1 [ required: >=8.7.1 ]
├── deprecated 1.2.14 [ required: Any ]
│   └── wrapt 1.16.0 [ required: <2,>=1.10 ]
├── lxml 4.9.3 [ required: >=4.8 ]
├── packaging 23.2 [ required: Any ]
└── pillow 10.1.0 [ required: >=10.0.1 ]
requests 2.31.0 [ required: >=2.31.0 ]
├── certifi 2023.11.17 [ required: >=2017.4.17 ]
├── charset-normalizer 3.3.2 [ required: <4,>=2 ]
├── idna 3.6 [ required: <4,>=2.5 ]
└── urllib3 2.1.0 [ required: <3,>=1.21.1 ]

pdm list --freeze以requirements格式列出

$ pdm list --freeze
certifi==2023.11.17
charset-normalizer==3.3.2
Deprecated==1.2.14
idna==3.6
lxml==4.9.3
packaging==23.2
pikepdf==8.7.1
Pillow==10.1.0
requests==2.31.0
urllib3==2.1.0
wrapt==1.16.0

pdm list --json以json格式列出

$ pdm list --json
[
    {
        "name": "pikepdf",
        "version": "8.7.1",
        "location": ""
    },
    {
        "name": "lxml",
        "version": "4.9.3",
        "location": ""
    },
    {
        "name": "packaging",
        "version": "23.2",
        "location": ""
    },
    {
        "name": "Deprecated",
        "version": "1.2.14",
        "location": ""
    },
    {
        "name": "Pillow",
        "version": "10.1.0",
        "location": ""
    },
    {
        "name": "wrapt",
        "version": "1.16.0",
        "location": ""
    }
]

删除依赖库

使用pdm remove命令删除依赖库

$ pdm remove requests
Removing packages from default dependencies: requests
Changes are written to pyproject.toml.
🔒 Lock successful
Changes are written to pdm.lock.
Synchronizing working set with resolved packages: 0 to add, 0 to update, 6 to remove

  ✔ Remove idna 3.6 successful
  ✔ Remove certifi 2023.11.17 successful
  ✔ Remove charset-normalizer 3.3.2 successful
  ✔ Remove requests 2.31.0 successful
  ✔ Remove urllib3 2.1.0 successful
  ✔ Remove deprecation 2.1.0 successful

🎉 All complete!

更新依赖库

使用pdm update更新所有依赖,使用pdm update <包名>更新指定包

# 更新所有包
pdm update

# 更新某个包
pdm update <包名>

分组更新

# 更新dev依赖下test分组中的pytest包
pdm update -dG pytest

查看项目环境

使用pdm info查看项目信息

$ pdm info -v
PDM version:
  2.10.4
Python Interpreter:
  /Users/xx/code/tbase_upgrade_oss_manual/.venv/bin/python (3.11)
Project Root:
  /Users/xx/code/tbase_upgrade_oss_manual
Local Packages:

切换Python解释器

使用pdm use来切换Python解释器,但要满足两个条件:

  1. 只能切换到当前操作系统上拥用的解释器版本,pdm use命令会列出所有适用的版本。
  2. pdm init时已经限制过解释器版本的哈,则只能满足该版本的前提下切换。例如:在pdm init时设置过requires-python = ">=3.11",则pdm use的参数也必须满足>=3.11否则会失败。
$ pdm use 3.10
Interpreters found but not matching:
  - /Users/xx/.rye/py/cpython@3.10.9/install/bin/python3 (3.10)
[NoPythonVersion]: No python is found meeting the requirement python >=3.11

$ pdm use 3.12
[NoPythonVersion]: No Python interpreter matching 3.12 is found.

$ pdm use
Please enter the Python interpreter to use
0. /Users/xx/code/tbase_upgrade_oss_manual/.venv/bin/python (3.11)
1. /Users/xx/software/Python-3.11.4/bin/python3.11 (3.11)
2. /Users/xx/.rye/py/cpython@3.11.1/install/bin/python3 (3.11)
Please select (0):

运行python命令

如果想在pdm配置的环境中,运行python命令或文件,可使用pdm run

$ pdm run python -V
Python 3.11.4
$ pdm run python -c 'print("hello")'
hello
$ pdm run python hello.py
hello

命令别名

当命令比较复杂时,可以配置命令别名来简化使用难度,有点类似NodeJS中package.json里面的scripts

pdm的命令别名配置在pyproject.toml[tool.pdm.scripts],如需快捷设置,只用编辑该模块。

$ grep -A 1 "tool.pdm.scripts" pyproject.toml
[tool.pdm.scripts]
start = "python -c 'print(\"hello\")'"

$ pdm start
hello

pdm支持多种类型(cmd/shell/call/composite)的命令别名,以及诸多命令选项(env/env_file/site_packages等),更多信息参照PDM Scripts

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值