使用click进行python下命令行工具的编写以及编码问题解决

用原生的参数解析工具非常繁琐,而click工具入手就非常简单了,而且直观。建立以下这个程序a.py[1], cli会有子命令make,make有选项--work:

  1 import click
  2 
  3 @click.group()
  4 def cli():
  5     print("cli")
  6 
  7 @cli.command()
  8 @click.option('--work', default=None)
  9 def make(work):
 10     print(type(work))
 11     print(work)
 12 
 13 if __name__ == '__main__':
 14     cli()

a.py在bash下执行:

$ python a.py
Usage: a.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  make

在bash下执行:

$ python a.py make
cli

None

a.py在bash下执行:

$ python a.py make --work='我'
cli

a.py修改, 增加make的参数name:

  7 @cli.command()
  8 @click.option('--work', default=None)
  9 @click.argument('name')
 10 def make(work, name):
 11     print(u'work: {}, type: {}'.format(work, type(work)))
 12     print(u'name: {}'.format(name))

在bash下执行:

$ python a.py make --work='我'
cli
Usage: a.py make [OPTIONS] NAME
Try "a.py make --help" for help.

Error: Missing argument "NAME".

注意执行时提示:Error: Missing argument "NAME"。 表示需要参数NAME。我们重新执行:

$ python a.py make --work='我' '张三'
cli
work: 我, type: 
name: 张三

可以用click.Choice限定参数或者选项的取值范围,修改代码:

  7 @cli.command()
  8 @click.option('--work', default=None, type=click.Choice(['全职', '兼职']))
  9 @click.argument('name')
 10 def make(work, name):
 11     print(u'work: {}, type: {}'.format(work, type(work)))
 12     print(u'name: {}'.format(name))

我们重新执行:

$ python a.py make --work='全' '张三'
cli
/home/jzhou/env/wf/lib/python2.7/site-packages/click/types.py:156: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
 if value in self.choices:
/home/jzhou/env/wf/lib/python2.7/site-packages/click/types.py:176: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
 if normed_value in normed_choices:
Traceback (most recent call last):
 File "a.py", line 16, in 
   cli()
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/core.py", line 764, in __call__
   return self.main(*args, **kwargs)
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/core.py", line 717, in main
   rv = self.invoke(ctx)
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/core.py", line 1135, in invoke
   sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/core.py", line 641, in make_context
   self.parse_args(ctx, args)
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/core.py", line 940, in parse_args
   value, args = param.handle_parse_result(ctx, opts, args)
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/core.py", line 1469, in handle_parse_result
   value = self.full_process_value(ctx, value)
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/core.py", line 1790, in full_process_value
   return Parameter.full_process_value(self, ctx, value)
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/core.py", line 1438, in full_process_value
   value = self.process_value(ctx, value)
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/core.py", line 1428, in process_value
   return self.type_cast_value(ctx, value)
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/core.py", line 1417, in type_cast_value
   return _convert(value, (self.nargs != 1) + bool(self.multiple))
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/core.py", line 1415, in _convert
   return self.type(value, self, ctx)
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/types.py", line 39, in __call__
   return self.convert(value, param, ctx)
 File "/home/jzhou/env/wf/lib/python2.7/site-packages/click/types.py", line 180, in convert
   (value, ', '.join(self.choices)), param, ctx)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 16: ordinal not in range(128)

这个是因为click在python 2环境下没有考虑把参数或者选项转化为unicode,下载click_patch[2], clone后在目录下安装:

$ git clone https://github.com/fininfotech/click_patch.git
Cloning into 'click_patch'...
remote: Enumerating objects: 11, done.
remote: Counting objects: 100% (11/11), done.
remote: Compressing objects: 100% (8/8), done.
remote: Total 11 (delta 1), reused 8 (delta 1), pack-reused 0
Unpacking objects: 100% (11/11), done.
$ cd click_patch
$ python setup.py install
running install
....

修改a.py:

  1 # -*- coding:utf-8 -*-
  2 import click
  3 import click_patch
  4 
  5 @click.group()
  6 def cli():
  7     print("cli")
  8 
  9 @cli.command()
 10 @click.option('--work', default=None, type=click.Choice([u'全职', u'兼职']))
 11 @click.argument('name')
 12 def make(work, name):
 13     print(u'work: {}, type: {}'.format(work, type(work)))
 14     print(u'name: {}'.format(name))
 15 
 16 if __name__ == '__main__':
 17     cli()

继续执行:

$ python a.py make --work='全' '张三'
cli
Usage: a.py make [OPTIONS] NAME
Try "a.py make --help" for help.

Error: Invalid value for "--work": invalid choice: 全. (choose from 全职, 兼职)
$ python a.py make --work='全职' '张三'
cli
work: 全职, type: 
name: 张三

总的来说,click用来做命令行工具非常方便,但是在python 2.7环境下还存在一些字符编码上的问题,可以使用click_patch来改正。


  1. 本文所有代码在fedora 27环境下测试,python 2.7.15。 ↩

  2. click_patch目前只是参考实现,不建议在生产上使用,如果要在生产上用,请务必自己确认和测试代码。 ↩

你可能感兴趣的:(使用click进行python下命令行工具的编写以及编码问题解决)