要处理转义字符,可以使用如下回调:
代码:
import codecs
def unescape(ctx, param, value):
return codecs.getdecoder("unicode_escape")(value)[0]
要使用回调,可以执行以下操作:
@click.argument('escaped', callback=unescape)
这个怎么用
这将使用
unicode_escape
编解码器。
(
Source
)
测试代码:
import click
@click.command()
@click.argument('escaped', callback=unescape)
def cli(escaped):
click.echo('len: {}, ord: {}'.format(len(escaped), ord(escaped)))
if __name__ == "__main__":
commands = (
r'\t',
r'\n',
'\t',
',',
'--help',
)
import sys, time
time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for cmd in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + cmd)
time.sleep(0.1)
cli(cmd.split())
except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc, (click.ClickException, SystemExit)):
raise
结果:
Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> \t
len: 1, ord: 9
-----------
> \n
len: 1, ord: 10
-----------
>
Usage: test.py [OPTIONS] ESCAPED
Error: Missing argument "escaped".
-----------
> ,
len: 1, ord: 44
-----------
> --help
Usage: test.py [OPTIONS] ESCAPED
Options:
--help Show this message and exit.