![]() |
argparse and imported modules - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: argparse and imported modules (/thread-14460.html) |
argparse and imported modules - spatialdawn - Dec-01-2018 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: Any explanations and hints would be welcome! Thanks! RE: argparse and imported modules - Gribouillis - Dec-01-2018 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.
RE: argparse and imported modules - spatialdawn - Dec-01-2018 Great, thank you! |