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

python click module for command line interface的更多相关文章

  1. Install the AWS Command Line Interface on Linux

    Install the AWS Command Line Interface on Linux You can install the AWS Command Line Interface and i ...

  2. MySQL 5.6 Warning: Using a password on the command line interface can be insecure

    MySQL 5.6 在命令行输入密码,就会提示这些安全警告信息. Warning: Using a password on the command line interface can be inse ...

  3. MySQL 5.6 警告信息 command line interface can be insecure 修复

    在命令行输入密码,就会提示这些安全警告信息. Warning: Using a password on the command line interface can be insecure.   注: ...

  4. atprogram.exe : Atmel Studio Command Line Interface

    C:\Program Files\Atmel\Atmel Studio 6.1\atbackend\atprogram.exe No command specified.Atmel Studio Co ...

  5. Centos下_MysqL5.7在使用mysqldump命令备份数据库报错:mysqldump: [Warning] Using a password on the command line interface can be insecure.

    在阿里云服务器增加一个shell脚本定时备份数据库脚本执行任务时,测试性的执行了备份命令,如下 [root@iZ2ze503xw2q1fftv5rhboZ mysql_bak]# /usr/local ...

  6. Warning: Using a password on the command line interface can be insecure.

    [root@qttc ~]# /usr/local/mysql/bin/mysqldump  -uroot -proot db > bak.sqlWarning: Using a passwor ...

  7. mysql 备份报错mysqldump: [Warning] Using a password on the command line interface can be insecure.

    -------------------------------------------------------------------------------- mysql 备份报错mysqldump ...

  8. vue-cli 脚手架 Command Line Interface

    mac sudo npm install -g nrm sudo npm config -g set unsafe-perm sudo npm install webpack@3.0.0 -g sud ...

  9. MYSQL5.7脚本运行时出现[Warning] Using a password on the command line interface can be insecure

    MYSQL版本:5.7 在写linux脚本执行MYSQL命令的时候,如果使用 MYSQL="mysql -hlocalhost -P3306 -uroot -p666666" 登陆 ...

随机推荐

  1. 理解JavaScript的作用域链

    上一篇文章中介绍了Execution Context中的三个重要部分:VO/AO,scope chain和this,并详细的介绍了VO/AO在JavaScript代码执行中的表现. 本文就看看Exec ...

  2. Bootstrap系列 -- 9. 表格

    一. Bootstrap 表格样式支持 Bootstrap提供了六种不同风格的样式支持,其中一个基础样式,4个附件样式,1个响应式设计样式 1. .table:基础表格 2. .table-strip ...

  3. 使用windbg查看DependencyObject的属性

    这里以WPF作为探测用的例子,简单一些,看看Title的值是什么样子.(之所以写这个,因为不是简单的一个!do就能看到东西的,中间要绕两下,这也涉及到了DependencyObject的实现机制及数据 ...

  4. AJAX——核心XMLHttpRequest对象

    AJAX大家已经都知道了,是为了实现异步通讯,提高用户体验度,而将很多旧知识(XML,DOM,JavaScript,HTML,Jquery,Css……)重新融合的一个新的知识框架.而,XMLHttpR ...

  5. :after,:before

    :after和:before生成的内容具有内联元素的属性,在不设置display:block的情况下设置宽高无效 :after和:before生成的内容具有absolute的性质,默认都是以父元素的左 ...

  6. 一步一步教你elasticsearch在windows下的安装

    首先下载最新的elasticsearch安装版本:elasticsearch下载.下载最新的elasticsearch 0.90.1版本.下载完成后.解压缩在安装目录.在cmd命令行进入安装目录,再进 ...

  7. 概率DP light oj 1030

    t组数据 n块黄金 到这里就捡起来 出发点1 到n结束  点+位置>n 重掷一次 dp[i] 代表到这里的概率 dp[i]=(dp[i-1]+dp[i-2]... )/6  如果满6个的话 否则 ...

  8. 浅谈我对JCS 的理解

    JCS 是Java 中缓存的一种实现,支持将数据缓存到内存和硬盘中,支持设置缓存对象的有效时长. 我认为可以这么理解JCS:客户端向服务器发出请求,服务器就先去缓存中查一下有没有客户端请求的数据,有则 ...

  9. 系统间通信(3)——IO通信模型和JAVA实践 上篇

    来源:http://blog.csdn.net/yinwenjie 1.全文提要 系统间通信本来是一个很大的概念,我们首先重通信模型开始讲解.在理解了四种通信模型的工作特点和区别后,对于我们后文介绍搭 ...

  10. C#6.0新特性的尝试

    由于项目升级到了.NetFramework 4.6.1,开发工具转向了vs2015,趁机尝试下C#6.0.结果在网上搜的一些教程总结的不是太完整,有的代码随着vs正式版的发布也有所修改.那些个教程也没 ...