【问题标题】:Python optparse not working for mePython optparse 不适合我
【发布时间】:2010-04-21 16:27:50
【问题描述】:

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

【问题讨论】:

    标签: python optparse


    【解决方案1】:

    args 变量保存所有未分配给选项的参数。通过将Kelvin 分配给person 选项变量,您的代码确实可以正常工作。

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

    另见the documentation on optparse

    parse_args() 返回两个值:

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

    【讨论】:

    • 哦,我明白了。我阅读了帮助文档,但我想我必须仔细阅读才能完全理解。谢谢!哇,第一次来,很快就得到了回复。
    • 你应该选择一个答案,让人们知道你是值得信赖的,下次你也会得到快速响应!
    【解决方案2】:

    根据optparse求助:

    "成功时返回一对 (values, args),其中 'values' 是一个 Values 实例(包含所有选项值),而 'args' 是解析选项后剩余的参数列表。”

    尝试hello.py -p Kelving abcd - 'Kelvin' 将被 optparse 解析,'abcd' 将落在argsparse_args 返回的变量中

    【讨论】:

      【解决方案3】:

      注意:“选项”是包含您添加的选项的字典。 “Args”是一个包含未解析参数的列表。你不应该看长度“args”。这里有一个成绩单来说明:

      moshez-mb:profile administrator$ cat foo
      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()
      moshez-mb:profile administrator$ python foo
      
      [Debug]: Print options: {'person': 'Me'}
      
      [Debug]: Print args: []
      
      Usage: foo [options]
      
      Options:
        -h, --help            show this help message and exit
        -p PERSON, --person=PERSON
      moshez-mb:profile administrator$ python foo -p Moshe
      
      [Debug]: Print options: {'person': 'Moshe'}
      
      [Debug]: Print args: []
      
      Usage: foo [options]
      
      Options:
        -h, --help            show this help message and exit
        -p PERSON, --person=PERSON
      moshez-mb:profile administrator$ python foo -p Moshe argument
      
      [Debug]: Print options: {'person': 'Moshe'}
      
      [Debug]: Print args: ['argument']
      
      Hello Moshe
      moshez-mb:profile administrator$ 
      

      【讨论】:

        【解决方案4】:
        import ast
        
        (options, args) = parser.parse_args()
        noargs = ast.literal_eval(options.__str__()).keys()
        if len(noargs) != 1:
            parser.error("ERROR: INCORRECT NUMBER OF ARGUMENTS")
            sys.exit(1)
        

        【讨论】:

        • 我不确定 ast 模块与 args 变量为何为空​​有关。参数数量不正确,只是分配方式不同。
        • 能否请您告诉我代码有什么问题。顺便说一句,这是一种解决方法...我无法使 len(args) 使其正常工作....不确定我是否我错过了一些东西。
        • 它没有解决问题,发帖人问为什么args 是空的。答案是 args 应该为空,因为 optparser 就是这样工作的。您的代码将添加 'person' 键并显示它,但这不是这里应该发生的。
        猜你喜欢
        • 2011-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多