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()
输出:
>C:\Scripts\example>hello.py -p Kelvin
[Debug]: Print options: {'person': 'Kelvin'}
[Debug]: Print args: []
Usage: hello.py [options]
选项: -h, --help 显示此帮助消息并退出 -p 人,--人=人
I'm currently learning on how to use the Python optparse module. I'm trying the following example script but the args variable comes out empty. I tried this using Python 2.5 and 2.6 but to no avail.
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()
Output:
>C:\Scripts\example>hello.py -p Kelvin
[Debug]: Print options: {'person': 'Kelvin'}
[Debug]: Print args: []
Usage: hello.py [options]
Options:
-h, --help show this help message and exit
-p PERSON, --person=PERSON
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
args
变量保存未分配给选项的任何参数。通过将Kelvin
分配给person
选项变量,您的代码确实可以正常工作。如果您尝试运行
hello.py -p Kelvin file1.txt
,您会发现person
仍然被分配了值“Kelvin”
,并且那么你的args
将包含“file1.txt”
。另请参阅有关
optparse
的文档:The
args
variable holds any arguments that were not assigned to an option. Your code is indeed working properly by assigningKelvin
to theperson
option variable.If you tried running
hello.py -p Kelvin file1.txt
, you would find thatperson
still was assigned the value"Kelvin"
, and then yourargs
would contain"file1.txt"
.See also the documentation on
optparse
:根据
optparse
帮助:“成功时返回一对 (values, args),其中 'values' 是 Values 实例(包含所有选项值),'args' 是参数列表 解析选项后剩下的。”
尝试
hello.py -p Kelving abcd
- 'Kelvin' 将由 optparse 解析,'abcd' 将落在parse_args
返回的args
变量中According to
optparse
help:"On success returns a pair (values, args) where 'values' is an Values instance (with all your option values) and 'args' is the list of arguments left over after parsing options."
Try
hello.py -p Kelving abcd
- 'Kelvin' will be parsed by optparse, 'abcd' will land inargs
variable returned byparse_args
注意:“选项”是包含您添加的选项的字典。 “Args”是包含未解析参数的列表。您不应该查看长度“args”。这是一个文字记录来说明:
Note: "options" is a dictionary with the options you added. "Args" is a list with the unparsed arguments. You should not be looking at length "args". Here is a transcript to illustrate: