Python Forum

Full Version: argparse and imported modules
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there,

I am having an issues with parsing arguments and I don't quite understand what's happening.

I have two files, 'a.py' & 'b.py'

a.py contains functions that shall be called from b.py, but a.py also runs stand-alone in some use cases.

a.py parses arguments with argparse from a parent file:

 
import argparse
parser = argparse.ArgumentParser(parents=[argparse_parent_base.parser])
args = parser.parse_args()

def foo()
   ...

def bar()
   ...

if __name__ == '__main__':
   ...
This works fine.

b.py also uses the arguments from the parent file, imports b.py AND is supposed to support an additional argument:


import argparse
import b 

if __name__ == '__main__':
    parser = argparse.ArgumentParser(parents=[argparse_parent_base.parser])
    parser.add_argument('-s', dest='some_variable')
    args = parser.parse_args()
When I call b.py with all arguments provided in the parent (-c, -p) and the additional one, I get:

Error:
usage: b.py [-h] [-c] [-p] b.py: error: unrecognized arguments: -s foo
Any explanations and hints would be welcome!

Thanks!
Arguments parsing occurs only when the code runs parser.parse_args(). This statement must be protected by the if __name__ == '__main__' in a.py. Also in b.py, you need to import a instead of b and you can use parents = [a.parser] in the ArgumentParser's constructor.
Great, thank you!