Domanda

Sto realizzando uno script piuttosto semplice che prende i seguenti parametri:

-p --port integer, optional, default 5050
-f --fork boolean, optional, default False
action string, required, needs to be either start or stop

Ho provato a implementarlo in Argparse, ma non è una mano di aiuto quando non viene fornita la stringa di azione, non riesce a fallire tutto ciò che è brutto:

usage: __init__.py [-h] [-p PORT] [-f] {start,stop}
__init__.py: error: argument action: invalid choice: '__init__.py' (choose from 'start', 'stop')

Anche quando passo "start" o "fermati", non riesce con lo stesso messaggio. Ecco il mio codice:

parser = argparse.ArgumentParser(description="Start or stop the server.",
    epilog="If you don't know what you're doing, run. Run for your life.\n")
parser.add_argument("-p", "--port", type=int, nargs=1, default=5050,
    dest="port", help="The port to run the server on.")
parser.add_argument("-f", "--fork", action="store_true", default=False,
    dest="fork", help="Fork to background? Default is false.")
parser.add_argument("action", type=str, choices=("start","stop"), help="Whether to 'start' or 'stop' the server.")

Cosa sto facendo di sbagliato qui? Spero che le mie intenzioni siano abbastanza chiare dal mio codice.

È stato utile?

Soluzione

Quale versione di Python stai usando? Quando eseguo il tuo codice con 2.7.1 funziona bene.

$ ./t stop
$ ./t start
$ ./t -f start
$ ./t -f stop
$ ./t -f
usage: someprog [-h] [-p PORT] [-f] {start,stop}
someprog: error: too few arguments
$ ./t -f -p 8080
usage: someprog [-h] [-p PORT] [-f] {start,stop}
someprog: error: too few arguments
$ ./t -f -p 8080 start

Un suggerimento, se si specifica "prog" nel cTOR è possibile prevalerlo utilizzando dentro.py come nome file

parser = argparse.ArgumentParser(
    prog="someprog",
    description="Start or stop the server.",
    epilog="If you don't know what you're doing, run. Run for your life.\n"
)

Inoltre, è Stampa l'utilizzo, ma non il lungo aiuto .. potresti fare qualcosa del genere per rendere le cose un po 'più ovvie ..

try:
    parser.parse_args()
except Exception e:
    print "************************"
    parser.print_help()
    print "************************"

Altri suggerimenti

Quando vengono forniti argomenti non validi, il Modulo ArgParse è progettato per stampare un messaggio di utilizzo e una descrizione del problema, quindi uscire, che è esattamente ciò che sta accadendo nel tuo esempio.

Se vuoi invece stampare un messaggio di aiuto, dovrai gestire questo caso da solo. Ad esempio, questo codice stamperà il messaggio di aiuto nel caso in cui non venga fornita alcuna azione:

parser = argparse.ArgumentParser(description="Start or stop the server.",
    epilog="If you don't know what you're doing, run. Run for your life.\n",
    prog="myserver")
parser.add_argument("-p", "--port", type=int, nargs=1, default=5050,
    dest="port", help="The port to run the server on.")
parser.add_argument("-f", "--fork", action="store_true", default=False,
    dest="fork", help="Fork to background? Default is false.")
parser.add_argument("action", nargs="?", type=str, choices=("start","stop"),
    help="Whether to 'start' or 'stop' the server.")

args = parser.parse_args()
if args.action is None:
    parser.print_help()
    sys.exit(1)

Se lo eseguo senza azione, ottengo:

$ python s.py
usage: myserver [-h] [-p PORT] [-f] [{start,stop}]

Start or stop the server.

positional arguments:
  {start,stop}          Whether to 'start' or 'stop' the server.

optional arguments:
  -h, --help            show this help message and exit
  -p PORT, --port PORT  The port to run the server on.
  -f, --fork            Fork to background? Default is false.

If you don't know what you're doing, run. Run for your life.

Tuttavia, se lo eseguo con un'azione non valida o un argomento non valido, allora ritorna al comportamento previsto del modulo ArgParse:

 $ python s.py not_valid
usage: myserver [-h] [-p PORT] [-f] [{start,stop}]
myserver: error: argument action: invalid choice: 'not_valid' (choose from 'start', 'stop')
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top