2017-08-28 1 views
0

J'utilise python ArgumentParser pour gérer les entrées utilisateur d'un programme CLI. Qui est un script pratique nommé smtp_mailer.py pour envoyer des emails via le protocole SMTP. Je souhaite utiliser l'outil CLI de deux manières:python ArgumentParser requis arguments facultatifs après que parse_known_args ne fonctionne pas correctement

  1. ./smtp_mailer.py <JSON representation of the mail>;
  2. ./smtp_mailer.py -u <user> -p <pass> -f <from> -t <to> ...

Alors, je suis utilise un analyseur pour analyser un argument de position json. Si elle n'a pas été fourni, je poursuis l'analyse syntaxique pour <user>/<port>/... arguments optionnels:

def parse_args(): 
    # the positional argument `json` 
    parser = ArgumentParser(add_help=False) 
    parser.add_argument('json', nargs='?', help='json representation of the SMTP mail') 
    args, remaining_argv = parser.parse_known_args() 

    if args.json: 
     return args 

    # the optional arguments 
    parent = parser 
    parser = ArgumentParser(parents=[parent], description='Send plain text mail through SMTP protocol.') 
    parser.add_argument('-H', '--host', type=str, help='SMTP host') 
    parser.add_argument('-P', '--port', type=int, help='SMTP port') 
    parser.add_argument('-u', '--user', type=str, required=True, help='SMTP username') 
    parser.add_argument('-p', '--pass', type=str, required=True, help='SMTP password') 

    parser.add_argument('-f', '--from', type=str, required=True, help='mail FROM') 
    parser.add_argument('-t', '--to', type=str, required=True, help='mail TO') 
    parser.add_argument('-c', '--cc', type=str, help='mail CC') 
    parser.add_argument('-s', '--subject', type=str, required=True, help='mail SUBJECT') 
    parser.add_argument('-b', '--body', type=str, required=True, help='mail BODY') 
    parser.add_argument('-a', '--attachments', type=str, help='mail ATTACHMENTS') 
    return parser.parse_args(remaining_argv) 

def main(): 
    print parse_pargs() 

Mais l'analyseur semble ne fonctionne pas correctement comme je m'y attendais si je n'ai pas fourni l'argument json.

./smtp_mailer.py -u "Ggicci" 
# output: 
Namespace(json='Ggicci') 

Cependant, je me attendre à voir:

usage: smtp_mailer.py [-h] [-H HOST] [-P PORT] -u USER -p PASS -f FROM -t TO 
         [-c CC] -s SUBJECT -b BODY [-a ATTACHMENTS] 
smtp_mailer.py: error: argument -p/--pass is required 

Répondre

0

Le parse_known_args met '-u' dans remaining_argv et 'Ggicci' dans args.

Depuis json est un '?' positionnel, toute chaîne sans drapeau compte comme valeur, et s'il n'y en a aucune, 'nothing' correspond également. Votre test serait plus fiable si vous définissiez un argument --json.