python argh/argparse: Comment puis-je passer d'une liste comme un argument de ligne de commande?

Je suis en train de passer d'une liste d'arguments d'un script python à l'aide de la argh bibliothèque. Quelque chose qui peut prendre des intrants tels que:

./my_script.py my-func --argA blah --argB 1 2 3 4
./my_script.py my-func --argA blah --argB 1
./my_script.py my-func --argA blah --argB 

Mon code ressemble à ceci:

import argh

@argh.arg('--argA', default="bleh", help='My first arg')
@argh.arg('--argB', default=[], help='A list-type arg--except it\'s not!')
def my_func(args):
    "A function that does something"

    print args.argA
    print args.argB

    for b in args.argB:
        print int(b)*int(b)  #Print the square of each number in the list
    print sum([int(b) for b in args.argB])  #Print the sum of the list

p = argh.ArghParser()
p.add_commands([my_func])
p.dispatch()

Et voici comment il se comporte:

$ python temp.py my-func --argA blooh --argB 1
blooh
['1']
1
1

$ python temp.py my-func --argA blooh --argB 10
blooh
['1', '0']
1
0
1

$ python temp.py my-func --argA blooh --argB 1 2 3
usage: temp.py [-h] {my-func} ...
temp.py: error: unrecognized arguments: 2 3

Le problème semble assez simple: argh est seulement en acceptant le premier argument, et la traiter comme une chaîne de caractères. Comment puis-je faire "s'attendre à" une liste d'entiers à la place?

Je vois comment cela se fait dans optparse, mais que dire de la (non-déconseillé) argparse? Ou en utilisant argh est beaucoup plus agréable, décoré de la syntaxe? Ceux-ci semblent beaucoup plus pythonic.

InformationsquelleAutor Abe | 2012-02-22