首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解OptionParser

理解OptionParser
EN

Stack Overflow用户
提问于 2011-02-10 18:00:50
回答 3查看 65.5K关注 0票数 12

我正在试用optparse,这是我的初始脚本。

代码语言:javascript
复制
#!/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!!"

现在,我想做的就是:

  1. 如果该选项没有参数,它将采用“默认”值。例如,myScript.py -d将只列出当前目录,否则没有任何参数的-m将使用当前月份作为参数。
  2. 对于“-月”,只允许01到12作为论据。
  3. 想要组合多个选项来执行不同的任务,即myScript.py -d this_dir -m 02将做不同于单独的-d和-m的事情。
  4. 上面会写上“没有选择!”只有在脚本没有提供任何选项的情况下。

这些可行吗?我确实访问了doc.python.org站点,寻找可能的答案,但作为一个蟒蛇初学者,我发现自己迷失在页面中。非常感谢你的帮助,谢谢。干杯!!

更新: 16/01/11

我想我还漏掉了什么。这就是我现在剧本里的东西。

代码语言:javascript
复制
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()

我的目标是:

  1. 在没有任何选项的情况下运行脚本,将返回option.mon工作
  2. 使用-m选项运行脚本,并返回option.mon工作
  3. 运行只有-v选项的脚本,将只返回根本不工作的option.vos
  4. 使用-m和-v选择运行脚本,将做不同的事情来达到目的

当我只使用-m选项运行脚本时,它首先打印option.mon,然后打印option.vos,这是我根本不想要的。真的很感激有人能让我走上正确的方向。干杯!!

第三次更新

代码语言:javascript
复制
    #!/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)

这是脚本在使用各种选项运行时返回的内容:

代码语言:javascript
复制
# ./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'

我只想看到:

代码语言:javascript
复制
 1. `I'm 'Mac' and this month is 'Mar'` - as *result #3*  
 2. `My name is: Mac` - as *result #4*

我做错什么了?干杯!!

第4次更新:

回答自己:这样我就能得到我想要的东西,但我还是没印象。

代码语言:javascript
复制
#!/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

现在这个给了我我想要的东西

代码语言:javascript
复制
# ./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'

这是唯一的方法吗?在我看来不是“最好的方法”。干杯!!

EN

回答 3

Stack Overflow用户

发布于 2011-06-02 23:29:11

不建议使用optparse;您应该在python2和python3中使用argparse

http://docs.python.org/library/argparse.html#module-argparse

票数 3
EN

Stack Overflow用户

发布于 2014-05-11 00:32:58

你的解决方案在我看来是合理的。评论:

  • 我不明白为什么要把month_abbr变成元组;没有tuple(),它应该工作得很好
  • 我建议检查无效的月份值(如果您发现问题,请检查raise OptionValueError)
  • 如果您确实希望用户准确地输入"01“、"02”、.或"12",则可以使用“选择”选项类型;请参见选项类型文档
票数 2
EN

Stack Overflow用户

发布于 2015-08-13 13:35:56

只是为了说明选项--argparse.argumentParser的add_argument()-method:

代码语言:javascript
复制
#!/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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4960880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档