如何在脚本中实现--verbose或-v选项? [英] How to implement the --verbose or -v option into a script?
问题描述
我从几种工具中知道--verbose
或-v
,我想在自己的一些脚本和工具中实现它.
I know the --verbose
or -v
from several tools and I'd like to implement this into some of my own scripts and tools.
我考虑过放置:
if verbose:
print ...
通过我的源代码,以便如果用户通过-v
选项,则变量verbose
将设置为True
并打印文本.
through my source code, so that if a user passes the -v
option, the variable verbose
will be set to True
and the text will be printed.
这是正确的方法还是更常见的方法?
Is this the right approach or is there a more common way?
添加:我没有要求实现参数解析的方法.我知道它是怎么做的.我只对详细选项特别感兴趣.
Addition: I am not asking for a way to implement the parsing of arguments. That I know how it is done. I am only interested specially in the verbose option.
推荐答案
我的建议是使用一个函数.但是不要将if
放在您可能会想做的函数中,而是这样做:
My suggestion is to use a function. But rather than putting the if
in the function, which you might be tempted to do, do it like this:
if verbose:
def verboseprint(*args):
# Print each argument separately so caller doesn't need to
# stuff everything to be printed into a single string
for arg in args:
print arg,
print
else:
verboseprint = lambda *a: None # do-nothing function
(是的,您可以在if
语句中定义一个函数,并且只有在条件为true时才会被定义!)
(Yes, you can define a function in an if
statement, and it'll only get defined if the condition is true!)
如果您使用的是Python 3,其中print
已经是一个函数(或者如果您愿意使用from __future__ import print_function
在2.x中将print
用作函数),则它甚至更简单:
If you're using Python 3, where print
is already a function (or if you're willing to use print
as a function in 2.x using from __future__ import print_function
) it's even simpler:
verboseprint = print if verbose else lambda *a, **k: None
这样,如果关闭了详细模式(使用lambda),则该函数被定义为不执行任何操作",而不是不断测试verbose
标志.
This way, the function is defined as a do-nothing if verbose mode is off (using a lambda), instead of constantly testing the verbose
flag.
如果用户可以在程序运行期间更改详细模式 ,这将是错误的方法(您需要在函数中使用if
),但是由于使用命令行标志进行设置,您只需做出一次决定即可.
If the user could change the verbosity mode during the run of your program, this would be the wrong approach (you'd need the if
in the function), but since you're setting it with a command-line flag, you only need to make the decision once.
然后使用verboseprint("look at all my verbosity!", object(), 3)
每当您要打印详细"消息时.
You then use e.g. verboseprint("look at all my verbosity!", object(), 3)
whenever you want to print a "verbose" message.
这篇关于如何在脚本中实现--verbose或-v选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!