了解OptionParser

Mac*_*ers 10 python optparse optionparser

我正在尝试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!!"
Run Code Online (Sandbox Code Playgroud)

现在,这就是我要做的事情:

  1. 如果没有给出该选项的参数,它将采用"默认"值.即myScript.py -d只列出当前目录或-m没有任何参数将当前月份作为参数.
  2. 对于"--month",只允许01到12作为参数
  3. 想要结合多个选项来执行不同的任务,即myScript.py -d this_dir -m 02与-d和-m作为个体做不同的事情.
  4. 只有在脚本没有提供选项的情况下,它才会打印" 没有选项! ".

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


更新:16/01/11

我想我还在遗漏一些东西.这就是我脚本中的内容.

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()
Run Code Online (Sandbox Code Playgroud)

这些是我的目标:

  1. 没有任何选项运行脚本,将返回option.mon[ 工作 ]
  2. 使用-m选项运行脚本,返回option.mon[ working ]
  3. 使用ONLY -v选项运行脚本,只返回option.vos[ 根本不工作 ]
  4. 使用-m和-v选择运行脚本,会做不同的事情[ 尚未达到目的 ]

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


第三次更新

    #!/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)
Run Code Online (Sandbox Code Playgroud)

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

# ./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'
Run Code Online (Sandbox Code Playgroud)

我只想看到:

 1. `I'm 'Mac' and this month is 'Mar'` - as *result #3*  
 2. `My name is: Mac` - as *result #4*
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?干杯!!


第四次更新:

回答自己:这样我可以得到我正在寻找的东西,但我仍然没有留下深刻的印象.

#!/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
Run Code Online (Sandbox Code Playgroud)

现在这给了我正是我想要的东西:

# ./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'
Run Code Online (Sandbox Code Playgroud)

这是唯一的方法吗?对我来说不是"最好的方式".干杯!!

nin*_*cko 3

optparse已弃用;你应该argparse在 python2 和 python3 中使用

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

  • 该链接说新的 2.7 因此 2.6 你仍然使用 optparse (7认同)