0

I want to give my script named console parameters in any order, but my code won't work as it should.

import argparse, sys

parser = argparse.ArgumentParser()
parser.add_argument('n', help="some integer which is needed", type=int, default=100)
parser.add_argument('b', help="a yes or no question (default yes)", type=str, default=True)
args=parser.parse_args()
print(args)

I want to be able to do all of the following things which are all failing in their own unique annoying ways:

  • python myscript.py n=85
  • python myscript.py b=No
  • python myscript.py b=No n=47

all result in an invalid int error and it is driving me up the wall. Why can't I just tell the script what n and b are in the order I like? Why can't I give the value of a parameter with its name? Why are my default values totally ignored? Also python myscript.py 7458 b=yes

is also not much better it prints Namespace(n=7458, b='b=yes')

so why can't I say something like n=7458, why is b= not understood to be not part of the b value?

  • With `n` and `b` you have defined `positional` arguments, that don't take a flag. "python myscript 47 foobar` should work. If you want to use flags, define the arguments with '-n` and '-b'. For '-b`' you might want to specify `action='store_true'. It's all there in the docs; you just need to spend a while longer reading them :) – hpaulj Feb 25 '21 at 23:52
  • Thanks. But how can I give -b a string input such that -b=no is valid, but the default is still true? – Lukas Schmidinger Feb 26 '21 at 00:03
  • What do you mean by valid? As defined you'll get `namespace(b="no")`, or what ever string you provide. Converting words like 'No', 'si' etc to `True/False` is up to you. `argarse` doesn't provide such an interpreter. – hpaulj Feb 26 '21 at 00:11
  • Several relevant docs sections: https://docs.python.org/3/library/argparse.html#name-or-flags, https://docs.python.org/3/library/argparse.html#type, https://docs.python.org/3/library/argparse.html#action – hpaulj Feb 26 '21 at 05:39

0 Answers0