per ottenere esattamente quello che stai cercando, il trucco è quello di utilizzare parse_known_args()
invece di parse_args()
:
#!/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', action="store_true")
parser.add_argument('-b', action="store_true")
opts = parser.parse_known_args()
# Print info about flags
if opts[0].a: print('You set the option "-a"')
if opts[0].b: print('You set the option "-b"')
# Collect remainder (opts[1] is a list (possibly empty) of all remaining args)
if opts[1]: print('You passed the strings %s' % opts[1])
EDIT:
Il codice precedente visualizza le seguenti informazioni di aiuto:
./clargs.py -h
usage: clargs_old.py [-h] [-a] [-b]
optional arguments:
-h, --help show this help message and exit
-a
-b
Se si desidera informare l'utente sull'argomento arbitrario facoltativo, l'unica soluzione che posso pensare è sottoclasse ArgumentParser e scrivilo in te stesso
Ad esempio:
#!/bin/env python
import os
import argparse
class MyParser(argparse.ArgumentParser):
def format_help(self):
help = super(MyParser, self).format_help()
helplines = help.splitlines()
helplines[0] += ' [FOO]'
helplines.append(' FOO some description of FOO')
helplines.append('') # Just a trick to force a linesep at the end
return os.linesep.join(helplines)
parser = MyParser()
parser.add_argument('-a', action="store_true")
parser.add_argument('-b', action="store_true")
opts = parser.parse_known_args()
# Print info about flags
if opts[0].a: print('You set the option "-a"')
if opts[0].b: print('You set the option "-b"')
# Collect remainder
if opts[1]: print('You passed the strings %s' % opts[1])
che visualizza le seguenti informazioni di aiuto:
./clargs.py -h
usage: clargs.py [-h] [-a] [-b] [FOO]
optional arguments:
-h, --help show this help message and exit
-a
-b
FOO some description of FOO
nota l'aggiunta del [FOO]
nella linea di "utilizzo" e il FOO
nella Guida sotto "argomenti opzionali ".
Hai seguito il tutorial di argparse? Tutto ciò che stai descrivendo è lì – SheetJS
L'unica parte non discussa di iirc è il comportamento 'nargs =" * "' (in modo che un argomento posizionale possa afferrare tutti gli argomenti rimanenti) – SheetJS
@Nirk, La cosa complicata è che se usi semplicemente 'parse_args', non appena vede un argomento" posizionale ", smette di cercare gli altri argomenti e raggruppa gli argomenti dall'argomento posizionale alla fine. Questo nella maggior parte dei casi va bene, ma romperebbe il suo primo e terzo esempio. – jedwards