Python 理解OptionParser
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4960880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
understanding OptionParser
提问by MacUsers
I was trying out optparseand this is my initial script.
我正在尝试optparse,这是我的初始脚本。
#!/usr/bin/env python
import os, sys
from optparse import OptionParser
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"
parser.add_option("-d", "--dir", type="string",
help="List of directory",
dest="inDir", default=".")
parser.add_option("-m", "--month", type="int",
help="Numeric value of the month",
dest="mon")
options, arguments = parser.parse_args()
if options.inDir:
print os.listdir(options.inDir)
if options.mon:
print options.mon
def no_opt()
print "No option has been given!!"
Now, this is what I'm trying to do:
现在,这就是我想要做的:
- If no argument is given with the option, it will take the "default" value.
i.e
myScript.py -dwill just list the present directory or-mwithout any argument will take the current month as an argument. - For the "--month" only 01 to 12 are allowed as an argument
- Want to combine more than one option for performing different tasks i.e.
myScript.py -d this_dir -m 02will do different thing than -d and -m as individual. - It will print "No option has been given!!" ONLY if no option is supplied with the script.
- 如果选项没有给出参数,它将采用“默认”值。即
myScript.py -d只列出当前目录或-m不带任何参数将当前月份作为参数。 - 对于“--month”,只允许 01 到 12 作为参数
- 想要组合多个选项来执行不同的任务,即
myScript.py -d this_dir -m 02会做与 -d 和 -m 不同的事情作为单独的。 - 仅当脚本未提供任何选项时,它才会打印“ No option has been given!!”。
Are these doable? I did visit the doc.python.org site for possible answers, but as a python-beginner, I found myself lost in the pages. It's very much appreciated your help; thanks in advance. Cheers!!
这些可行吗?我确实访问了 doc.python.org 站点以获得可能的答案,但作为 Python 初学者,我发现自己迷失在这些页面中。非常感谢您的帮助;提前致谢。干杯!!
Update: 16/01/11更新:16/01/11
I think I'm still missing something. This is the thing in my script now.
我想我仍然缺少一些东西。这就是我现在脚本中的内容。
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"
parser.add_option("-m", "--month", type="string",
help="select month from 01|02|...|12",
dest="mon", default=strftime("%m"))
parser.add_option("-v", "--vo", type="string",
help="select one of the supported VOs",
dest="vos")
options, arguments = parser.parse_args()
These are my goal:
这些是我的目标:
- run the script without any option, will return
option.mon[working] - run the script with -m option, with return
option.mon[working] - run the script with ONLY -v option, will ONLY return
option.vos[not working at all] - run the script with -m and -v opting, will do different thing [yet to get to the point]
- 不带任何选项运行脚本,将返回
option.mon[ working] - 使用 -m 选项运行脚本,并返回
option.mon[ working] - 使用 ONLY -v 选项运行脚本,只会返回
option.vos[根本不工作] - 使用 -m 和 -v 选项运行脚本,会做不同的事情 [尚未达到重点]
When I run the script with only -m option, it's printing option.monfirst and then option.vos, which I don't want at all. Really appreciate if anyone can put me in the right direction. Cheers!!
当我只使用 -m 选项运行脚本时,它option.mon先打印,然后打印option.vos,我根本不想要。如果有人能让我朝着正确的方向前进,真的很感激。干杯!!
3rd Update第三次更新
#!/bin/env python
from time import strftime
from calendar import month_abbr
from optparse import OptionParser
# Set the CL options
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"
parser.add_option("-m", "--month", type="string",
help="select month from 01|02|...|12",
dest="mon", default=strftime("%m"))
parser.add_option("-u", "--user", type="string",
help="name of the user",
dest="vos")
options, arguments = parser.parse_args()
abbrMonth = tuple(month_abbr)[int(options.mon)]
if options.mon:
print "The month is: %s" % abbrMonth
if options.vos:
print "My name is: %s" % options.vos
if options.mon and options.vos:
print "I'm '%s' and this month is '%s'" % (options.vos,abbrMonth)
This is what the script returns when run with various options:
这是脚本在使用各种选项运行时返回的内容:
# ./test.py
The month is: Feb
#
# ./test.py -m 12
The month is: Dec
#
# ./test.py -m 3 -u Mac
The month is: Mar
My name is: Mac
I'm 'Mac' and this month is 'Mar'
#
# ./test.py -u Mac
The month is: Feb
My name is: Mac
I'm 'Mac' and this month is 'Feb'
I like to see only:
我只喜欢看:
1. `I'm 'Mac' and this month is 'Mar'` - as *result #3*
2. `My name is: Mac` - as *result #4*
what am I doing wrong? Cheers!!
我究竟做错了什么?干杯!!
4th Update:第四次更新:
Answering to myself: this way I can get what I'm looking for but I'm still not impressed though.
对自己回答:这样我就可以得到我想要的东西,但我仍然没有留下深刻的印象。
#!/bin/env python
import os, sys
from time import strftime
from calendar import month_abbr
from optparse import OptionParser
def abbrMonth(m):
mn = tuple(month_abbr)[int(m)]
return mn
# Set the CL options
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"
parser.add_option("-m", "--month", type="string",
help="select month from 01|02|...|12",
dest="mon")
parser.add_option("-u", "--user", type="string",
help="name of the user",
dest="vos")
(options, args) = parser.parse_args()
if options.mon and options.vos:
thisMonth = abbrMonth(options.mon)
print "I'm '%s' and this month is '%s'" % (options.vos, thisMonth)
sys.exit(0)
if not options.mon and not options.vos:
options.mon = strftime("%m")
if options.mon:
thisMonth = abbrMonth(options.mon)
print "The month is: %s" % thisMonth
if options.vos:
print "My name is: %s" % options.vos
and now this gives me exactly what I was looking for:
现在这给了我我正在寻找的东西:
# ./test.py
The month is: Feb
# ./test.py -m 09
The month is: Sep
# ./test.py -u Mac
My name is: Mac
# ./test.py -m 3 -u Mac
I'm 'Mac' and this month is 'Mar'
Is this the only way of doing so? Doesn't look the "best way" to me. Cheers!!
这是唯一的方法吗?对我来说看起来不是“最佳方式”。干杯!!
回答by ninjagecko
optparseis deprecated; you should use argparsein both python2 and python3
optparse已弃用;你应该argparse在 python2 和 python3 中使用
http://docs.python.org/library/argparse.html#module-argparse
http://docs.python.org/library/argparse.html#module-argparse
回答by jrennie
Your solution looks reasonable to me. Comments:
你的解决方案在我看来是合理的。注释:
- I don't understand why you turn
month_abbrinto a tuple; it should work fine without thetuple() - I'd recommend checking for invalid month value (
raise OptionValueErrorif you find a problem) - if you really want the user to input exactly "01", "02", ..., or "12", you could use the "choice" option type; see option types documentation
- 我不明白为什么你变成
month_abbr了一个元组;没有它应该可以正常工作tuple() - 我建议检查无效的月份值(
raise OptionValueError如果您发现问题) - 如果您确实希望用户准确输入“01”、“02”、...或“12”,则可以使用“选择”选项类型;请参阅选项类型文档
回答by feinmann
Just to illustrate the choices-option of argparse.ArgumentParser's add_argument()-method:
只是为了说明 argparse.ArgumentParser 的 add_argument() 方法的选择选项:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from argparse import ArgumentParser
from datetime import date
parser = ArgumentParser()
parser.add_argument("-u", "--user", default="Max Power", help="Username")
parser.add_argument("-m", "--month", default="{:02d}".format(date.today().month),
choices=["01","02","03","04","05","06",
"07","08","09","10","11","12"],
help="Numeric value of the month")
try:
args = parser.parse_args()
except:
parser.error("Invalid Month.")
sys.exit(0)
print "The month is {} and the User is {}".format(args.month, args.user)

