gpt4 book ai didi

Python optparse 不适合我

转载 作者:太空狗 更新时间:2023-10-30 02:14:17 25 4
gpt4 key购买 nike

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

最佳答案

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

如果您尝试运行 hello.py -p Kelvin file1.txt,您会发现 person 仍然被分配了值 "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, then options.file will be the filename supplied by the user, or None if the user did not supply that option
  • args, the list of positional arguments leftover after parsing options

关于Python optparse 不适合我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2684732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com