2014-06-08 13 views
9

Próbuję mieć wymaganą wykluczającą się grupę z jednym wymaganym parametrem. Poniżej znajduje się kod, który mam umieścićPython argparse: Wymaga wzajemnie wymagana grupa z wymaganą opcją

#!/usr/bin/python 

import argparse 
import sys 

# Check for the option provided as part of arguments 
def parseArgv(): 
    parser = argparse.ArgumentParser() 
    group = parser.add_mutually_exclusive_group() 
    group.add_argument("-v", "--verbose", choices=[1,2,3,4], 
      help = "Increase verbosity") 
    group.add_argument("-q", "--quiet", action="store_true", help = "Run quietly") 
    name = parser.add_mutually_exclusive_group(required=True) 
    name.add_argument("-n", "--name", help = "Name of the virtual machine") 
    name.add_argument("-t", "--template", help = "Name of the template to use \ 
      for creating vm. If path is not provided then it will be looked \ 
      under template directory.") 
    parser.add_argument("-s", "--save", help = "Save the machine template. If \ 
      path is not provided then it will be saved under template directory."); 
    #parser.add_argument("-k", "--kick_start", required = True, help = "Name of the \ 
    #  kick start file. If path is not provided then it will be look into http \ 
    #  directory.") 
    if len(sys.argv) == 1: 
     parser.print_help() 
    args = parser.parse_args() 

if __name__ == '__main__': 
    parseArgv() 

Teraz wyjście z tego programu, jak postępować

$ python test.py 
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE] 

optional arguments: 
    -h, --help   show this help message and exit 
    -v {1,2,3,4}, --verbose {1,2,3,4} 
         Increase verbosity 
    -q, --quiet   Run quietly 
    -n NAME, --name NAME Name of the virtual machine 
    -t TEMPLATE, --template TEMPLATE 
         Name of the template to use for creating vm. If path 
         is not provided then it will be looked under template 
         directory. 
    -s SAVE, --save SAVE Save the machine template. If path is not provided 
         then it will be saved under template directory. 
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE] 
test.py: error: one of the arguments -n/--name -t/--template is required 

ale gdybym un komentarza z linii 20 - 22 to zmiana wyjściowej poniżej

$ python test.py 
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE] -k 
       KICK_START 

optional arguments: 
    -h, --help   show this help message and exit 
    -v {1,2,3,4}, --verbose {1,2,3,4} 
         Increase verbosity 
    -q, --quiet   Run quietly 
    -n NAME, --name NAME Name of the virtual machine 
    -t TEMPLATE, --template TEMPLATE 
         Name of the template to use for creating vm. If path 
         is not provided then it will be looked under template 
         directory. 
    -s SAVE, --save SAVE Save the machine template. If path is not provided 
         then it will be saved under template directory. 
    -k KICK_START, --kick_start KICK_START 
         Name of the kick start file. If path is not provided 
         then it will be look into http directory. 
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE] -k 
       KICK_START 
test.py: error: argument -k/--kick_start is required 

Ale chcę, że albo -n/-t wraz z -k stają się obowiązkowe. Jak osiągnąć to samo.

Odpowiedz

6

Osiągnąłeś już to! Argparse wypisuje tylko pierwszy znaleziony błąd, więc chociaż może wyglądać tak, jakby to było tylko sprawdzanie -k, to w rzeczywistości wymaga również -n/-t. Możesz to zobaczyć, podając argument -k.

Jeśli podasz argument -k, komunikat o błędzie zmieni się z test.py: error: argument -k/--kick_start is required na test.py: error: one of the arguments -n/--name -t/--template is required.

+0

Dzięki, nie wiedziałem o tym, ponieważ uczę się Pythona :). Jeszcze jedna rzecz, jak sprawdzić, czy argument ma jakąś wartość. Czy istnieje jakaś pusta funkcja podobna do C++. – Abhinav

+0

Naprawdę powinieneś zadać osobne pytanie, jeśli nie jest ono powiązane (oczywiście po sprawdzeniu, czy nie zostało już zadane), ale ... To zależy od tego, co dokładnie chcesz zrobić. Python ma pojęcie "prawdy", więc możesz po prostu [użyć zmiennej bezpośrednio w klauzuli typu "if" lub cokolwiek innego] (https://docs.python.org/2/library/stdtypes.html#truth-value-testing), np. 'if variable:' lub 'if not variable:'. Poza tym możesz użyć np. 'len (zmienna) == 0' na kontenerach lub' zmienna ma wartość None', aby sprawdzić, czy nie ma konkretnej opcji. Lub po prostu porównaj z pustą wartością dla danego typu. –

+0

Domyślną wartością argumentów 'argparse' jest' Brak'. Zatem 'print args.name is None' wyświetli' True'. Domyślnie dla 'args.quiet' jest' False'. – hpaulj

Powiązane problemy