Python Forum
argparse and imported modules
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
argparse and imported modules
#1
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!
Reply
#2
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.
Reply
#3
Great, thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Bug argparse io issue pyDream 8 563 Apr-02-2024, 12:42 PM
Last Post: pyDream
  Sharing imported modules with Sub Processes? Stubblemonster 2 1,492 May-02-2022, 06:42 AM
Last Post: Stubblemonster
  Visual Studio Code Intellisense for Imported Modules Not Working hockinsk 1 2,698 Apr-23-2022, 04:41 PM
Last Post: deanhystad
  Can a module tell where it is being imported from? stevendaprano 3 1,163 Apr-12-2022, 12:46 AM
Last Post: stevendaprano
  Not able to figure out what is wrong with argparse radioactive9 31 8,451 Mar-16-2022, 07:50 PM
Last Post: deanhystad
  module detecting if imported vs not Skaperen 1 1,658 Nov-19-2021, 07:43 AM
Last Post: Yoriz
  [newbie] Why is a module imported twice? Winfried 3 4,060 Apr-02-2021, 04:48 AM
Last Post: deanhystad
Star NameError – function doesn't recognize imported modules Sir 4 3,467 Dec-01-2020, 06:36 AM
Last Post: Sir
  argparse --help in one line. Denial 1 1,965 Sep-20-2020, 03:38 PM
Last Post: deanhystad
  Argparse error when inputting values tqader 2 2,859 Sep-11-2020, 07:42 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020