Dynamicly assign argparse version number python

356 views Asked by At

I want to add a dynamic version to my code. I've got the following working code:

import argparse

VERSION = 0.2

parser = argparse.ArgumentParser(prog='PDF Generator')
parser.add_argument('-v', '--version', action='version', version='%(prog)s version 0.1')

args = parser.parse_args()

when I run the -v option, it gives me the static text (0.1) how do I change this text so that the global variable is used instead ?

When I use this code:

import argparse

VERSION = 0.2

parser = argparse.ArgumentParser(prog='PDF Generator')
parser.add_argument('-v', '--version', action='version', version='%(prog)s version %f' %VERSION)

args = parser.parse_args()

it raises a TypeError: format requires a mapping

Any help would be appreciated.

1

There are 1 answers

0
Anand S Kumar On BEST ANSWER

You can also use the concatenation operator of string instead of string formatting like -

parser.add_argument('-v', '--version', action='version', version='%(prog)s version ' + str(VERSION))

Or as answered in the comment by Lukasz , you can use String.format as -

parser.add_argument('-v', '--version', action='version', version='%(prog)s version {}'.format(VERSION))

Version is replaced at the first occurrence of {}