Skip to content
Advertisement

Python argparse – user defined Action with ‘store_true’ behavoiur

Hi I suppose that i have parser argument which cannot pass any value, for example:

JavaScript

And my user defined action:

JavaScript

When i trying call this without any values:

JavaScript

I receive this error message:

JavaScript

I know that i can add action ‘store_true’ to my argument, but in this solution i cannot redirect execution of this argument to my defined action class.

Is someone know how to modify FooAction to achieve ‘store_true” action behaviour?

edit

class Fooaction with set nargs=0:

JavaScript

Advertisement

Answer

JavaScript

sample run:

JavaScript

Using your init

JavaScript

add_argument returns the Action object it created. We usually ignore it, but saving it to a reference, and printing it can be handy during debugging.

Even though the Action subclasses are marked as ‘private’ (with _) it’s a good idea to look at their code to see how they customize the base class. Action class by itself doesn’t do much. The default action uses _StoreAction. Store True/False subclass _StoreConst. _HelpAction is the only one that does not store some sort of value in the namespace; and it does a system exit.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement