Skip to content Skip to sidebar Skip to footer

Is There A Way To Clear Python Argparse?

Consider the following script: import argparse parser1 = argparse.ArgumentParser() parser1.add_argument('-a') args1 = parser1.parse_args() parser2 = argparse.ArgumentParser() pars

Solution 1:

Your scenario is quite unclear, but I guess what you're looking for is parse_known_args

Here I guessed that you called init.py from the other files, say caller1.py and caller2.py

Also suppose that init.py only parses -a argument, while the original script will parse the rest.

You can do something like this:

in init.py put this in do_things method:

parser = argparse.ArgumentParser()
parser.add_argument('-a')
parsed = parser.parse_known_args(sys.argv)
print'From init.py: %s' % parsed['a']

In caller1.py:

init.do_things(sys.argv)
parser = argparse.ArgumentParser()
parser.add_argument('-b')
parsed = parser.parse_known_args(sys.argv)
print'From caller1.py: %s' % parsed['b']

If you call caller1.py as follows: python caller1.py -a foo -b bar, the result will be:

From init.py: foo
From caller1.py: bar

But if your scenario is not actually like this, I would suggest to use @Michael0x2a answer, which is just to use single ArgumentParser object in caller1.py and pass the value appropriately for init.py

Solution 2:

  1. This doesn't really make sense, because for all intents and purposes, the parser object is stateless. There's nothing to clear, since all it does is takes in the console arguments, and returns a Namespace object (a pseudo-dict) without ever modifying anything in the process.

    Therefore, you can consider parse_args() to be idempotent. You can repeatedly call it over and over, and the same output will occur. By default, it will read the arguments from sys.argv, which is where the console arguments are stored.

    However, note that you can pipe in custom arguments by passing in a list to the parse_args function so that the parser will using something other then sys.argv as input.

  2. I'm not sure what you mean. If you call python myscript.py -a 15, args1 will equal Namespace(a='15'). You can then do args1['a'] to obtain the value of 15. If you want to make the flag act as a toggle, call parser.add_argument('-a', action='store_true'). Here is a list of all available actions.

  3. I would try and confine all the console/interface code into a single module and into a single parser. Basically, remove the code to parse the command line from init.py and the second file into an independent little section. Once you run the parser, which presents a unified interface for everything in your program, pass in the appropriate variables to functions inside init.py. This has the added advantage of keeping the UI separate and more easily interchangeable with the rest of the code.

Post a Comment for "Is There A Way To Clear Python Argparse?"