Python optparse不适合我

Neb*_*10z 4 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() 
Run Code Online (Sandbox Code Playgroud)

输出:

>C:\Scripts\example>hello.py -p Kelvin

[Debug]: Print options: {'person': 'Kelvin'}

[Debug]: Print args: []

Usage: hello.py [options]
Run Code Online (Sandbox Code Playgroud)

选项:-h, - help显示此帮助消息并退出-p PERSON, - person = PERSON

Mar*_*off 7

args变量包含未分配给选项的任何参数.您的代码确实是分配正常工作Kelvinperson选项变量.

如果您尝试运行hello.py -p Kelvin file1.txt,您会发现person仍然分配了值"Kelvin",然后您args将包含"file1.txt".

另见以下文档optparse:

parse_args() 返回两个值:

  • options,一个包含所有选项值的对象 - 例如,如果--file采用单个字符串参数,那么options.file将是用户提供的文件名,或者None如果用户没有提供该选项
  • args,解析选项后剩余的位置参数列表