Skip to content

Commit 3d0edf4

Browse files
committed
docs(user_guide): update command system documentation
- Remove outdated information about argument parsing - Add detailed explanation of help system - Update code examples and clarify command structure - Improve formatting and organization of the document
1 parent 490e7f7 commit 3d0edf4

5 files changed

Lines changed: 432 additions & 129 deletions

File tree

docs/user_guide/argument.zh.md

Lines changed: 283 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,283 @@
1+
# 参数解析
2+
3+
参数解析系统提供了从函数签名构建`ArgumentParser`的功能。这是一个相对独立的组件,通过与命令组件类`Command`集成来进入`ptcmd`框架。
4+
5+
## 基本示例
6+
7+
使用`@auto_argument`装饰器是最简单的声明式参数解析方式。它会自动分析函数的参数签名,并创建相应的`ArgumentParser`实例:
8+
9+
```python linenums="1"
10+
from ptcmd import Cmd, auto_argument
11+
12+
class MyApp(Cmd):
13+
@auto_argument
14+
def do_hello(self, name: str = "World") -> None:
15+
"""Hello World!"""
16+
self.poutput(f"Hello, {name}!")
17+
```
18+
19+
在上面的例子中,`name`参数会自动转换为一个可选的位置参数,默认值为"World"。
20+
21+
## Argument类
22+
23+
`Argument` 是参数解析系统的核心类,用于以声明式方式定义命令行参数。它封装了 `argparse` 的参数配置,提供更 Pythonic 的接口。
24+
25+
### 基本用法
26+
27+
可以直接实例化 `Argument` 来定义参数:
28+
29+
```python linenums="1"
30+
from ptcmd import Argument
31+
32+
# 创建一个简单的字符串参数
33+
file_arg = Argument(
34+
"--file",
35+
type=str,
36+
help="输入文件路径"
37+
)
38+
39+
# 创建一个布尔标志参数
40+
verbose_arg = Argument(
41+
"-v", "--verbose",
42+
action="store_true",
43+
help="启用详细输出"
44+
)
45+
```
46+
47+
### 参数配置
48+
49+
`Argument` 支持所有标准 `argparse` 参数配置,常用参数如下:
50+
51+
| 参数 | 描述 | 示例 |
52+
|------|------|------|
53+
| `action` | 指定参数动作 | `action="store_true"` |
54+
| `nargs` | 参数数量 | `nargs='*'` |
55+
| `const` |`nargs``action` 配合使用的常量值 | `const="value"` |
56+
| `default` | 默认值 | `default=0` |
57+
| `type` | 参数类型转换函数 | `type=int` |
58+
| `choices` | 允许的参数值列表 | `choices=["a", "b"]` |
59+
| `required` | 是否必需 | `required=True` |
60+
| `help` | 帮助文本 | `help="输入文件路径"` |
61+
| `metavar` | 在帮助消息中显示的参数名称 | `metavar="FILE"` |
62+
| `dest` | 存储参数值的目标属性名 | `dest="output_file"` |
63+
| `version` |`action="version"` 配合使用的版本号 | `version="1.0.0"` |
64+
65+
例如,定义一个需要多个输入文件的参数:
66+
67+
```python linenums="1"
68+
files: Arg[
69+
list,
70+
"--files",
71+
{"nargs": "*", "type": str, "help": "输入文件列表"}
72+
]
73+
```
74+
75+
## 使用Arg类型注解
76+
77+
对于更复杂的参数定义,可以使用`Arg`类型提示。`Arg`允许指定参数的标志、帮助文本和其他属性:
78+
79+
```python linenums="1"
80+
from ptcmd import Cmd, Arg, auto_argument
81+
82+
class MathApp(Cmd):
83+
@auto_argument
84+
def do_add(
85+
self,
86+
x: float,
87+
y: float,
88+
*,
89+
verbose: Arg[bool, "-v", "--verbose", {"help": "详细输出"}] = False
90+
) -> None:
91+
"""两数相加"""
92+
result = x + y
93+
if verbose:
94+
self.poutput(f"{x} + {y} = {result}")
95+
else:
96+
self.poutput(result)
97+
```
98+
99+
`Arg`的语法格式为:`Arg[类型, 参数标志..., {参数属性}]`
100+
101+
- 类型:参数的数据类型(如`str``int``float``bool`等)
102+
- 参数标志:参数的命令行标志(如`"-v"``"--verbose"`
103+
- 参数属性:一个字典,包含参数的其他属性(如`help``choices`等),也可以使用一个`Argument`作为属性。
104+
105+
!!! note
106+
107+
`Arg`实际上是适用于类型检查器的简单转换,运行时与`Argument`类完全等价。但通常推荐`Arg`仅用于类型注解
108+
109+
## 使用Annotated和Argument类型注解
110+
111+
如果希望更严格的遵照代码风格检查器,可以使用标准的`Annotated``Argument`以规避`Arg`的语法报错:
112+
113+
```python linenums="1"
114+
from typing import Annotated
115+
from ptcmd import Cmd, Argument, auto_argument
116+
117+
class MathApp(Cmd):
118+
@auto_argument
119+
def do_add(
120+
self,
121+
x: float,
122+
y: float,
123+
*,
124+
verbose: Annotated[bool, Argument("-v", "--verbose", action="store_true")] = False
125+
) -> None:
126+
"""两数相加"""
127+
result = x + y
128+
if verbose:
129+
self.poutput(f"{x} + {y} = {result}")
130+
else:
131+
self.poutput(result)
132+
```
133+
134+
但通过这种方式定义的参数无法获得参数字段补全,需要自行在`Argument`指定所有需要的字段。
135+
136+
### 参数忽略
137+
138+
当某些参数不需要出现在命令行界面时,可以使用 `IgnoreArg` 类型来标记该参数应被忽略:
139+
140+
```python linenums="1"
141+
from ptcmd import Cmd, IgnoreArg, auto_argument
142+
143+
class App(Cmd):
144+
@auto_argument
145+
def do_process(
146+
self,
147+
input: str,
148+
internal_state: IgnoreArg[dict] = {}
149+
) -> None:
150+
"""处理输入数据,internal_state 仅用于内部状态管理"""
151+
# internal_state 不会出现在命令行参数中
152+
self.poutput(f"Processing {input}")
153+
```
154+
155+
在这个例子中,`internal_state` 参数将被完全忽略,不会添加到命令行解析器中。
156+
157+
## 参数解析
158+
159+
`ptcmd`会根据参数的类型和位置自动推断参数的行为:
160+
161+
1. 位置参数:函数的位置参数会转换为命令行的位置参数
162+
2. 可选参数:使用`*`分隔的关键字参数会转换为可选参数
163+
3. 布尔参数:类型为`bool`的参数会自动转换为标志参数(`store_true``store_false`
164+
4. 默认值:参数的默认值会传递给`ArgumentParser`
165+
166+
### 自动推断
167+
168+
参数解析可以根据类型注解和参数特征自动推断合适的 `argparse` 配置,减少手动配置。以下是关键的自动推断规则:
169+
170+
#### 布尔类型自动转换
171+
172+
系统会根据布尔参数的默认值自动选择 `store_true``store_false` 动作:
173+
174+
```python linenums="1"
175+
# 默认值为 False -> 自动使用 store_true
176+
verbose: Arg[bool] = False
177+
# 生成: parser.add_argument("--verbose", action="store_true")
178+
179+
# 默认值为 True -> 自动使用 store_false
180+
enabled: Arg[bool] = True
181+
# 生成: parser.add_argument("--enabled", action="store_false")
182+
183+
# 也可以显式指定标志
184+
debug: Arg[bool, "-d", "--debug"] = False
185+
# 生成: parser.add_argument("-d", "--debug", action="store_true")
186+
```
187+
188+
#### 位置参数与关键字参数的自动处理
189+
190+
系统会根据参数在函数签名中的位置自动决定是位置参数还是可选参数:
191+
192+
```python linenums="1"
193+
@auto_argument
194+
def do_process(
195+
self,
196+
input_file: str, # 位置参数(无默认值)
197+
output: str = "out", # 位置参数(带默认值)
198+
*,
199+
verbose: bool = False # 关键字参数 -> 可选参数
200+
) -> None:
201+
pass
202+
```
203+
204+
- 位置参数:函数签名中的位置参数(无`*`分隔符)会转换为命令行位置参数
205+
- 可选参数:使用`*`分隔的关键字参数会转换为命令行可选参数(必须使用`--`前缀)
206+
207+
#### Literal 类型的智能处理
208+
209+
当参数类型为 `Literal` 时,系统会自动设置 `choices`,并根据需要调整参数行为:
210+
211+
```python linenums="1"
212+
from typing import Literal
213+
214+
# 自动设置 choices
215+
level: Literal["debug", "info", "warning", "error"]
216+
217+
# 与默认值结合
218+
level: Literal["debug", "info", "warning", "error"] = "info"
219+
# 生成: parser.add_argument("--level", choices=..., default="info")
220+
221+
# 与关键字参数结合(自动成为可选参数)
222+
def do_set(
223+
self,
224+
*,
225+
level: Literal["debug", "info"] = "info"
226+
) -> None:
227+
pass
228+
# 生成: parser.add_argument("--level", ...)
229+
```
230+
231+
需要注意的是,如果在 `Argument` 中显式指定了 `choices` 参数,将覆盖 `Literal` 类型自动推导的选项:
232+
233+
#### 默认值的自动处理
234+
235+
默认值会直接影响参数的行为:
236+
237+
```python linenums="1"
238+
# 位置参数带默认值 -> 变为可选位置参数
239+
def do_example(self, file: str = "default.txt") -> None:
240+
pass
241+
# 生成: parser.add_argument("file", nargs="?", default="default.txt")
242+
243+
# 关键字参数带默认值 -> 标准可选参数
244+
def do_example(self, *, count: int = 1) -> None:
245+
pass
246+
# 生成: parser.add_argument("--count", type=int, default=1)
247+
```
248+
249+
### 处理未注解的参数
250+
251+
当函数参数未使用 `Arg``Argument` 进行注解时,`build_parser` 提供了三种处理模式,通过 `unannotated_mode` 参数控制:
252+
253+
- **strict**:严格模式,遇到未注解的参数时抛出 `TypeError`
254+
- **autoconvert**:自动转换模式,尝试根据类型注解推断参数配置
255+
- **ignore**:忽略模式,跳过未注解的参数
256+
257+
`@auto_argument` 装饰器默认使用**autoconvert**模式。在自动推断模式下,未被注解的参数`x: Tp`会被视为`x: Arg[Tp]`以自动推断参数信息。
258+
259+
```python linenums="1"
260+
@auto_argument(unannotated_mode="autoconvert")
261+
def do_convert(self, x: int, *, y: str = "y") -> None:
262+
...
263+
```
264+
265+
`autoconvert` 模式下,以上的代码会被视为
266+
267+
```python linenums="1"
268+
@auto_argument(unannotated_mode="autoconvert")
269+
def do_convert(self, x: Arg[int], *, y: Arg[str] = "y") -> None:
270+
...
271+
```
272+
273+
经过自动参数推断后,以上代码最终会转换为
274+
275+
```python linenums="1"
276+
@auto_argument(unannotated_mode="autoconvert")
277+
def do_convert(self, x: Annotated[int, Argument("x", type=int)], *, y: Annotated[str, Argument("-y", type=str, default="y")] = "y") -> None:
278+
...
279+
```
280+
281+
## 独立使用参数解析
282+
283+
参数解析

0 commit comments

Comments
 (0)