1

I'm writing a script in order to search for factorized numbers.

I want my script to accept 1 or 3 arguments, it should work only with:

  • python myscript.py -i
  • python myscript.py -e -n -o

Otherwise it should print --help.

Here is my code:

# --- Here we organize the choices command line aruments                
parser = argparse.ArgumentParser()                                      
parser.add_argument('-i', dest='input', help="input a pubilc key .pem file", metavar=None) 
parser.add_argument('-n', dest='modulus', help="value of modulus n (please input also -e and -o)", metavar=None)
parser.add_argument('-e', dest='exponent', help="value of exponent e (please input also -n and -o)", metavar=None)  
parser.add_argument('-o',dest='output', help="output a file name (please input also -n and -e)", metavar=None)                  
args = parser.parse_args()                                              

# --- Guide the user to the right choice ---                
if (len(sys.argv) == 1 and args.input != None):    # <-- problem must be around here I believe
    pass
elif (len(sys.argv) == 3 and args.modulus != None and args.exponent != None and args.output != None ):
    pass
else:
    parser.print_help()

But when I run python myscript.py -i first it prints the --help and then it execute the code.

It shouldn't print --help: everything is fine, I'm giving 1 argument and it's input

Francesco Mantovani
  • 10,216
  • 13
  • 73
  • 113

2 Answers2

2

I would use argparse's builtin parsing such as using subcommands (Python argparse mutual exclusive group) or use a mutually exclusive group:

import argparse

def main(parser, args):
    if args.meo is not None:
        modulus, exponent, output = args.meo
    print(args)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-i", help="Public key .pem file")
    group.add_argument("-meo", nargs=3, help="Modulus, exponent and output")
    main(parser, parser.parse_args())

Which results in:

~ python args.py -h
usage: args.py [-h] [-i I | -meo MEO MEO MEO]

optional arguments:
  -h, --help        show this help message and exit
  -i I              Public key .pem file
  -meo MEO MEO MEO  Modulus, exponent and output

~ python args.py -i input.pem
Namespace(i='input.pem', meo=None)

~ python args.py -meo X Y Z
Namespace(i=None, meo=['X', 'Y', 'Z'])
Alex
  • 6,610
  • 3
  • 20
  • 38
0

You are not counting your arguments properly, and the two command lines you give are invalid for your program. argparse is doing just what you told it: you gave it two invalid command lines, and got two sets of help docs.

You have arguments, not options. The correct formats are

python my_script.py -i FILE
python my_script.py -e 3 -m 16 -o my.log

The first line has 3 arguments; the second line has 7. Also, you need a group to handle the two cases properly.

Prune
  • 76,765
  • 14
  • 60
  • 81