Very useful thread. I had pretty much the same question as @Yan Zhu, @unutbu and @FacePalm's answeres were good, but I need to take in argv also. I came up with this, figured good because it allows me to write unit tests that don't require sys.argv arguments.
import argparse, sys
def parse(arg_list):
p = argparse.ArgumentParser(description="my simple app")
p.add_argument('-z', '--zeta', type=str, default='[zeta from default]')
p.add_argument('-a', '--application', type=str, default='[application from default]')
return p.parse_known_args(arg_list)
code_args = [ '-a', 'a from code', '-q', 'q from code', '-o', 'o from code']
print(parse(code_args + sys.argv[1:]))
When you add a runtime param from intellij like this -a 'a from intellij'
the results look like so.
/usr/local/bin/python3.7 /Users/me/IdeaProjects/co-util-py/test/varargstest.py -a "a from intellij"
(Namespace(application='a from intellij', other='o from code'), ['-q', 'q from code'])
You can see that argparse doesn't drop the q, but it also doesn't parse it.
Also, after lots of brain strain and testing, the only real difference between sys.argv and a list created is that sys.argv[0]
is the name of the program that is being called. Drop that from the list and it doesn't matter.