Python optparse对我无效

4

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

4个回答

7
args变量保存任何未分配给选项的参数。通过将Kelvin分配给person选项变量,您的代码确实正常工作。
如果您尝试运行hello.py -p Kelvin file1.txt,您会发现person仍然被赋予了值"Kelvin",然后您的args将包含"file1.txt"
另请参见optparse文档:

parse_args()返回两个值:

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

哦,我明白了。我读了帮助文档,但我想我需要仔细阅读才能完全理解。谢谢!哇,第一次来这里就得到了快速的回应。 - Nebu10z
你应该选择一个答案,这样人们就知道你是值得信赖的,下次你也会得到快速的回复! - Personman

1
根据 optparse 的帮助文档:

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

尝试运行 hello.py -p Kelving abcd - optparse 将解析 'Kelvin','abcd' 将会被返回的 parse_args 变量中的 args 列表接收。


0
注意: "options" 是您添加的选项字典。 "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$ 

0
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 变量为空有任何关系。参数的数量不正确,它们只是被分配了不同的值。 - Mike
请问您能否告诉我代码有什么问题。顺便说一下,这是一个解决方法...我无法使用len(args)使其工作....不确定是否漏掉了什么。 - Rama
1
它并没有回答问题,发帖者想知道为什么 args 是空的。答案是 args 应该 为空,因为这就是 optparser 的工作方式。你的代码会添加 'person' 键并显示它,但这不是本应该发生的事情。 - Mike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接