python 解析命令行_argparse --- 命令行选项、参数和子命令解析器 — Python 3.9.1 文档...

type¶

By default, the parser reads command-line arguments in as simple

strings. However, quite often the command-line string should instead be

interpreted as another type, such as a float or int. The

type keyword for add_argument() allows any

necessary type-checking and type conversions to be performed.

If the type keyword is used with the default keyword, the type converter

is only applied if the default is a string.

The argument to type can be any callable that accepts a single string.

If the function raises ArgumentTypeError, TypeError, or

ValueError, the exception is caught and a nicely formatted error

message is displayed. No other exception types are handled.

Common built-in types and functions can be used as type converters:

import argparse

import pathlib

parser = argparse.ArgumentParser()

parser.add_argument('count', type=int)

parser.add_argument('distance', type=float)

parser.add_argument('street', type=ascii)

parser.add_argument('code_point', type=ord)

parser.add_argument('source_file', type=open)

parser.add_argument('dest_file', type=argparse.FileType('w', encoding='latin-1'))

parser.add_argument('datapath', type=pathlib.Path)

User defined functions can be used as well:

>>>def hyphenated(string):

... return '-'.join([word[:4] for word in string.casefold().split()])

...

>>>parser = argparse.ArgumentParser()

>>>_ = parser.add_argument('short_title', type=hyphenated)

>>>parser.parse_args(['"The Tale of Two Cities"'])

Namespace(short_title='"the-tale-of-two-citi')

The bool() function is not recommended as a type converter. All it does

is convert empty strings to False and non-empty strings to True.

This is usually not what is desired.

In general, the type keyword is a convenience that should only be used for

simple conversions that can only raise one of the three supported exceptions.

Anything with more interesting error-handling or resource management should be

done downstream after the arguments are parsed.

For example, JSON or YAML conversions have complex error cases that require

better reporting than can be given by the type keyword. An

JSONDecodeError would not be well formatted and a

FileNotFound exception would not be handled at all.

Even FileType has its limitations for use with the type

keyword. If one argument uses FileType and then a subsequent argument fails,

an error is reported but the file is not automatically closed. In this case, it

would be better to wait until after the parser has run and then use the

with-statement to manage the files.

For type checkers that simply check against a fixed set of values, consider

using the choices keyword instead.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值