这更像是一个代码设计问题.对于文件的字符串/目录/全名类型的可选选项,什么是良好的默认值?
我们假设我有这样的代码:
import optparse
parser = optparse.OptionParser()
parser.add_option('-i', '--in_dir', action = "store", default = 'n', help = 'this is an optional arg')
(options, args) = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
然后我做:
if options.in_dir == 'n':
print 'the user did not pass any value for the in_dir option'
else:
print 'the user in_dir=%s' %(options.in_dir)
Run Code Online (Sandbox Code Playgroud)
基本上我想要有默认值,这意味着用户没有输入这样的选项与实际值.使用'n'是随意的,有更好的推荐吗?
你可以使用一个空字符串,""
Python将其解释为False
; 你可以简单测试:
if options.in_dir:
# argument supplied
else:
# still empty, no arg
Run Code Online (Sandbox Code Playgroud)
或者,使用None
:
if options.in_dir is None:
# no arg
else:
# arg supplied
Run Code Online (Sandbox Code Playgroud)
请注意,根据文档,后者是未提供参数的默认值.
归档时间: |
|
查看次数: |
5640 次 |
最近记录: |