mardi 21 novembre 2017

python - if optional arguments

I wish to able to pass multiple arguments with or without the use of -a or -b.

The script works as intended if I input no arguments, just -a / -b or multiple filenames without -a / -b

The use of -a results in the printing of -a (this part not wanted) and any further arguments.

The use of -b gives the 2nd error of requiring a second filename.

Do my problems stem from the use of multiple prints?

#!/usr/bin/env python3

import sys
if len(sys.argv) ==1:
    print ("\nerror: please enter at least one filename")
    sys.exit()

if len(sys.argv) ==2 and sys.argv[1]== "-a" or sys.argv[1] == "-b":
    print ("\nerror: please enter at least one filename after -a or -b")
    sys.exit()


if len(sys.argv) >=2 and sys.argv[1] != "-a" or sys.argv[1] != "-b":
    for arg in sys.argv[1:]:
        print(arg)

if len(sys.argv) >=2 and sys.argv[1] == "-b" or sys.argv[1] == "-b":
    for arg in sys.argv[2:]:
        print(arg)

Thank you for any and all help. I'm sorry if this wasn't clear enough.

Aucun commentaire:

Enregistrer un commentaire