我目前正在学习如何使用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 指定人名