设为首页 收藏本站
查看: 461|回复: 0

[经验分享] python click module for command line interface

[复制链接]

尚未签到

发表于 2015-12-1 09:22:56 | 显示全部楼层 |阅读模式
     Click Module(一)
                                                   ----xiaojikuaipao
  The following material was from the website  :
  http://click.pocoo.org/4/
  1. click Arguments
  website: http://click.pocoo.org/4/arguments/
  Arguments work similarly to options but are positional. They also only support a subset of the features of options due to their syntactical nature. Click will also not attempt to document arguments for you and wants you to document them manually in order to avoid ugly help pages.

1.1 Basic Arguments
  The most basic option is a simple string argument of one value. If no type is provided, the type of the default value is used, and if no default value is provided, the type is assumed to be STRING.
  Example:





@click.command()
@click.argument('filename')
def touch(filename):
click.echo(filename)

  And what it looks like:





$ touch foo.txt
foo.txt

1.2 Variadic Arguments
  The second most common version is variadic arguments where a specific (or unlimited) number of arguments is accepted. This can be controlled with the nargs parameter. If it is set to -1, then an unlimited number of arguments is accepted.
  The value is then passed as a tuple. Note that only one argument can be set to nargs=-1, as it will eat up all arguments.
  Example:





@click.command()
@click.argument('src', nargs=-1)
@click.argument('dst', nargs=1)
def copy(src, dst):
for fn in src:
click.echo('move %s to folder %s' % (fn, dst))

  And what it looks like:





$ copy foo.txt bar.txt my_folder
move foo.txt to folder my_folder
move bar.txt to folder my_folder

  Note that this is not how you would write this application. The reason for this is that in this particular example the arguments are defined as strings. Filenames, however, are not strings! They might be on certain operating systems, but not necessarily on all. For better ways to write this, see the next sections.



1.3  Note on Non-Empty Variadic Arguments
  If you come from argparse, you might be missing support for setting nargs to + to indicate that at least one argument is required.
This is supported by setting required=True. However, this should not be used if you can avoid it as we believe scripts should gracefully degrade into becoming noops if a variadic argument is empty. The reason for this is that very often, scripts are invoked with wildcard inputs from the command line and they should not error out if the wildcard is empty.
  1.4 File Arguments
  Since all the examples have already worked with filenames, it makes sense to explain how to deal with files properly. Command line tools are more fun if they work with files the Unix way, which is to accept - as a special file that refers to stdin/stdout.
  Click supports this through the click.File type which intelligently handles files for you. It also deals with Unicode and bytes correctly for all versions of Python so your script stays very portable.
  Example:





@click.command()
@click.argument('input', type=click.File('rb'))
@click.argument('output', type=click.File('wb'))
def inout(input, output):
while True:
chunk = input.read(1024)
if not chunk:
break
output.write(chunk)

  And what it does:





$ inout - hello.txt
hello
^D
$ inout hello.txt -
hello



1.5 File Path Arguments
  In the previous example, the files were opened immediately. But what if we just want the filename? The naïve way is to use the default string argument type. However, remember that Click is Unicode-based, so the string will always be a Unicode value. Unfortunately, filenames can be Unicode or bytes depending on which operating system is being used. As such, the type is insufficient.
  Instead, you should be using the Path type, which automatically handles this ambiguity. Not only will it return either bytes or Unicode depending on what makes more sense, but it will also be able to do some basic checks for you such as existence checks.
  Example:





@click.command()
@click.argument('f', type=click.Path(exists=True))
def touch(f):
click.echo(click.format_filename(f))

  And what it does:





$ touch hello.txt
hello.txt
$ touch missing.txt
Usage: touch [OPTIONS] F
Error: Invalid value for "f": Path "missing.txt" does not exist.




1.6 File Opening Safety
  The FileType type has one problem it needs to deal with, and that is to decide when to open a file. The default behavior is to be “intelligent” about it. What this means is that it will open stdin/stdout and files opened for reading immediately. This will give the user direct feedback when a file cannot be opened, but it will only open files for writing the first time an IO operation is performed by automatically wrapping the file in a special wrapper.
  This behavior can be forced by passing lazy=True or lazy=False to the constructor. If the file is opened lazily, it will fail its first IO operation by raising an FileError.
  Since files opened for writing will typically immediately empty the file, the lazy mode should only be disabled if the developer is absolutely sure that this is intended behavior.
  Forcing lazy mode is also very useful to avoid resource handling confusion. If a file is opened in lazy mode, it will receive a close_intelligently method that can help figure out if the file needs closing or not. This is not needed for parameters, but is necessary for manually prompting with the prompt() function as you do not know if a stream like stdout was opened (which was already open before) or a real file that needs closing.
  Starting with Click 2.0, it is also possible to open files in atomic mode by passing atomic=True. In atomic mode, all writes go into a separate file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.



1.7 Environment Variables
  Like options, arguments can also grab values from an environment variable. Unlike options, however, this is only supported for explicitly named environment variables.
  Example usage:





@click.command()
@click.argument('src', envvar='SRC', type=click.File('r'))
def echo(src):
click.echo(src.read())

  And from the command line:





$ export SRC=hello.txt
$ echo
Hello World!

  In that case, it can also be a list of different environment variables where the first one is picked.
  Generally, this feature is not recommended because it can cause the user a lot of confusion.



1.8 Option-Like Arguments
  Sometimes, you want to process arguments that look like options. For instance, imagine you have a file named -foo.txt. If you pass this as an argument in this manner, Click will treat it as an option.
  To solve this, Click does what any POSIX style command line script does, and that is to accept the string -- as a separator for options and arguments. After the -- marker, all further parameters are accepted as arguments.
  Example usage:





@click.command()
@click.argument('files', nargs=-1, type=click.Path())
def touch(files):
for filename in files:
click.echo(filename)

  And from the command line:





$ touch -- -foo.txt bar.txt
-foo.txt
bar.txt

  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-145708-1-1.html 上篇帖子: 基于七牛Python SDK写的一个批量下载脚本 下篇帖子: python 单元测试 unittest
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表