Python optparse不适合我
作者:互联网
我目前正在学习如何使用Python optparse模块.我正在尝试以下示例脚本,但args变量为空.我尝试使用Python 2.5和2.6,但无济于事.
import optparse
def main():
p = optparse.OptionParser()
p.add_option('--person', '-p', action='store', dest='person', default='Me')
options, args = p.parse_args()
print '\n[Debug]: Print options:', options
print '\n[Debug]: Print args:', args
print
if len(args) != 1:
p.print_help()
else:
print 'Hello %s' % options.person
if __name__ == '__main__':
main()
输出:
>C:\Scripts\example>hello.py -p Kelvin
[Debug]: Print options: {'person': 'Kelvin'}
[Debug]: Print args: []
Usage: hello.py [options]
选项:
-h, – help显示此帮助消息并退出
-p PERSON, – Person = PERSON
解决方法:
args变量包含未分配给选项的任何参数.通过将Kelvin分配给person选项变量,您的代码确实正常工作.
如果您尝试运行hello.py -p Kelvin file1.txt,您会发现仍然为该人分配了值“Kelvin”,然后您的args将包含“file1.txt”.
另见the documentation on optparse
:
parse_args()
returns two values:
options
, an object containing values for all of your options—e.g. if--file
takes a single string argument, thenoptions.file
will be the filename supplied by the user, orNone
if the user did not supply that optionargs
, the list of positional arguments leftover after parsing options
标签:python,optparse 来源: https://codeday.me/bug/20190610/1213496.html