argparse module - How to change help format in runtime?
Lets say, I've got a parser:
self.__parser = argparse.ArgumentParser(
prog = '<...>',
fromfile_prefix_chars='@')
After it is initializ开发者_如何学Goed I want in runtime to change the prog variable in argparser to something else, lets say: 'aaa'.
Code:
self.__parser.prog = 'aaa'
does NOT work, because argparser caches this prog somwhere inside ts formatters. Does somebody knows if is it possible to change this property in simple way?
It is my suspicion that the problem is somewhere else in your code, as the code below is allowed to change the prog attribute, demonstrated by the calls to print_help:
import argparse
import sys
class MyParser():
def __init__(self, nm=sys.argv[0]):
self.__parser = argparse.ArgumentParser(prog=nm, fromfile_prefix_chars='@')
def change_prog_name(self, nm):
self.__parser.prog = nm
def print_help(self):
self.__parser.print_help()
my_parser = MyParser()
my_parser.print_help()
print 'after prog change:'
my_parser.change_prog_name('aaa')
my_parser.print_help()
Output:
usage: argparse_test.py [-h]
optional arguments:
-h, --help show this help message and exitafter prog change:
usage: aaa [-h]optional arguments:
-h, --help show this help message and exit
精彩评论