2017-06-03 2 views
1

Hi Ich benutze ArgParse, um meine Argumente zu behandeln. Ich würde der Code wie ähnlichePython: ArgParse mit einem Hauptbefehl und Unterbefehl

# Main function 
$ myApp -i INPUT -o OUTPUT -s STUFF 

# Configure function 
$ myApp config -a conf1 -b conf2 

import argparse 
from argparse import RawTextHelpFormatter 

parser = argparse.ArgumentParser(description='myApp',formatter_class=RawTextHelpFormatter) 
parser.add_argument('-i',help='input',required=True) 
parser.add_argument('-o',help='output',required=True) 
parser.add_argument('-s',help='stuff',default=None,required=False) 
args = parser.parse_args() 

subp = parser.add_subparsers() 
conf_parser = subp.add_parser('config', help='configure') 
conf_parser.add_argument('-a',help='a config file',default=None,required=False) 
conf_parser.add_argument('-b',help='b config file',default=None,required=False) 
conf_args = conf_arser.parse_args() 

Hier zu arbeiten ist der Ausgang

python sandbox/test1.py --help 
usage: test1.py [-h] -i I -o O [-s S] 

myApp 

optional arguments: 
    -h, --help show this help message and exit 
    -i I  input 
    -o O  output 
    -s S  stuff 

Ich bin nicht die Config-args bekommen zu zeigen. Ich bin mir nicht sicher, was ich hier falsch mache.

Danke!

Antwort

3

es


import argparse 
from argparse import RawTextHelpFormatter 

parser = argparse.ArgumentParser(description='myApp',formatter_class=RawTextHelpFormatter) 
parser.add_argument('-i',help='input',required=True) 
parser.add_argument('-o',help='output',required=True) 
parser.add_argument('-s',help='stuff',default=None,required=False) 

subp = parser.add_subparsers(help='configure') 
conf_parser = subp.add_parser('config') 
conf_parser.add_argument('-a',help='a config file',default=None,required=False) 
conf_parser.add_argument('-b',help='b config file',default=None,required=False) 
args = parser.parse_args() 

python sandbox/test1.py --help 
usage: test1.py [-h] -i I -o O [-s S] {config} ... 

myApp 

positional arguments: 
    {config} configure 

optional arguments: 
    -h, --help show this help message and exit 
    -i I  input 
    -o O  output 
    -s S  stuff 

Gelöst
python sandbox/test1.py config --help 
usage: test1.py config [-h] [-a A] [-b B] 

optional arguments: 
    -h, --help show this help message and exit 
    -a A  a config file 
    -b B  b config file