2011-02-10 86 views
7

我正在嘗試optparse,這是我的初始腳本。瞭解OptionParser

#!/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. 對於「--month」只有01至12被允許作爲一個參數
  3. 想多一種選擇用於執行不同的任務,即myScript.py -d this_dir -m 02會做不同的事情莫過於-d和-m作爲單獨組合。
  4. 它將打印「沒有選項已被授予!!」只有腳本沒有提供任何選項。

這些可行嗎?我確實訪問了doc.python.org網站以獲得可能的答案,但作爲一名python初學者,我發現自己迷失在網頁中。非常感謝你的幫助;提前致謝。乾杯!!


更新: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() 

這是我的目標:

  1. 運行該腳本沒有任何選項,將返回option.mon [工作]
  2. 運行帶有-m選項的腳本,以回報option.mon [工作]
  3. 使用ONLY -v選項運行腳本,將只返回option.vos [不是w在工作會有所有]
  4. 運行帶有-m和-v選擇不予適用的腳本,會做不同的事情[還沒有切入正題]

當我運行只用-m選項的腳本,它首先打印option.mon,然後打印option.vos,這是我根本不需要的。真的很感謝任何人都可以把我放在正確的方向。乾杯!!


3日更新

#!/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) 

這是當各種選項來運行該腳本返回什麼:

# ./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' 

我只喜歡看:

1. `I'm 'Mac' and this month is 'Mar'` - as *result #3* 
2. `My name is: Mac` - as *result #4* 

什麼時我做錯了?乾杯!!


4日更新:

回答自己:這樣,我能得到什麼,我正在尋找,但我仍然沒有深刻的印象,雖然。

#!/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 

,現在這給了我正是我一直在尋找:

# ./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' 

這是這樣做的唯一途徑?不看我的「最佳方式」。乾杯!!

回答

1

你的解決方案看起來合理的我。評論:

  • 我不明白你爲什麼把month_abbr變成一個元組;它應該正常工作而不tuple()
  • 我建議你檢查無效月值(raise OptionValueError,如果你發現一個問題)
  • 如果你真的希望用戶輸入正是「01」,「02」,... ,或「12」,您可以使用「選擇」選項類型;看到option types documentation
0

只是爲了說明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)