VSN VSN -3 years ago 150
Python Question

How do you get the name of the program using argparse?

I am using

argparse
to parse command line arguments. While going through the documentation for
argparse
I could only see a provision to use a different program name.

I want to be able to use the default program name without having to import
sys
. There is nothing in
argparse
, as far as I can see, that will return the program name.

import argparse

parser = argparse.ArgumentParser()
args = parser.parse_args()

print(dir(args))


And here's the output:

['__class__', '__contains__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_args', '_get_kwargs']


Is there any other way of retrieving the program name without having to import the
sys
module?

Answer Source

ArgumentParserinstances have aprogattribute which I think is what you want.

import argparse

parser = argparse.ArgumentParser()
print('parser.prog: {}'.format(parser.prog))

I discovered this by reading the module's source code in Lib/argparse.py—specifically looking at the class ArgumentParser definition. Since the attribute's name doesn't start with an underscore character, I assume it's public.

Update

I see that, nowadays at least, that the prog attribute of ArgumentParser instance is (or has been since this question was asked) documented in both Python 2's documentation and Python 3's documentation.

So, yes, it's definitely public, and in both versions, if it is not supplied as a keyword argument when creating the ArgumentParser, it defaults to prog = _os.path.basename(_sys.argv[0]) (where _os and _sys are private argparse module attributes that correspond to their non-underscore-prefixed counterparts. Note that because of the use of os.basename(), this will only be the script's filename, not the complete path to it that may (it's OS dependent) have been in sys.argv[0].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download