How I can do conditional loop with argparse with variable nargs? So, basically, it should run with or without argument. I am trying:
parser = argparse.ArgumentParser(description="output parser")
group = parser.add_mutually_exclusive_group()
group.add_argument("--dos", help="get DOSCAR for plot",
nargs="?", metavar=("int"))
args = parser.parse_args()
if args.dos:
if len(args.dos) > 1:
chosen = int(args.dos[0])
chdos = "at_dos"+args.dos[0]+".dat"
else:
chosen = None
inpt = "DOSY"
print(chosen)
print(inpt)
Now, if I have variable, then its printing some value, wrong but some value:
$python3 vasp.py --dos 111
111
None # IT SHOULDN'T BE NONE
DOSY
but nothing without argument.
I have also tried with the normal sys.argv, as:
def get_dos():
if len(sys.argv) > 2:
chosen = int(sys.argv[2])
chdos = "at_dos"+sys.argv[2]+".dat"
else:
chosen = None
inpt = "DOSCAR"
print(sys.argv)
print(args.dos)
print(chosen)
print(inpt)
in this case, when option is present, its giving correct result:
python3 vasp.py --dos 12
['vasp.py', '--dos', '12']
12
12
DOSCAR
but again, nothing without option:
$python3 vasp.py --dos
I have tried with hpaulj's suggestion. It gives:
$python3 tt.py --dos 12
Namespace(dos='12')
1
DOSY
and without argument, its still not printing anything.
Nonewhen I run it and fix the invalid syntax. What version of Python are you using? I've tried both 3.5.1 and 2.7.11 and it works in both versions. You need a minimal reproducible example.len(args.dos) > 1does what you think it does. It checks if you've entered a number with more than 1 digit.print(args)to see directly what was parsed?--dosand without it at all?