Я пробовал 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!!"
Вот что я пытаюсь сделать do:
myScript.py -d
просто перечислит текущий каталог или -m
без каких-либо аргументов будет принимать текущий месяц в качестве аргумента. myScript.py -d this_dir -m 02
будет делать разные вещи, чем -d и -m по отдельности . Выполнимы ли это? Я посетил сайт doc.python.org для возможных ответов, но, как новичок в Python, я потерялся на страницах. Мы очень ценим вашу помощь; заранее спасибо. Ура !!
Кажется, я все еще что-то упускаю. Это сейчас в моем сценарии.
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()
Это моя цель:
option.mon
[ рабочий ] option.mon
[ working ] option.vos
[ не работает на все ] Когда я запускаю сценарий только с опцией -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)
Это то, что сценарий возвращает при запуске с различными параметрами:
# ./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*
что я делаю не так? Ура !!
Отвечая себе: таким образом я могу получить то, что ищу, но я все еще не впечатлен.
#!/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'
Это единственный способ сделать это? Мне кажется, это не лучший способ. Ура !!