Display newlines in help message when using python optparse

I use the optparse module to parse parameters / arguments. For backward compatibility reasons, I cannot use the argparse module. How can I format my epilog message to preserve newlines?

In the example below, I would like epilog to be printed as formatted.

epi = \ """ Examples usages: Do something %prog -a -b foo Do something else %prog -d -f -h bar """ parser = optparse.OptionParser(epilog=epi) 
+6
source share
3 answers

See the first answer at:

python optparse, how to include additional information in the decommissioning?

The main answer is to subclass OptionParser

 class MyParser(optparse.OptionParser): def format_epilog(self, formatter): return self.epilog 
+8
source

You can decorate optparse.HelpFormatter.format_description function:

 from optparse import HelpFormatter as fmt def decorate(fn): def wrapped(self=None, desc=""): return '\n'.join( [ fn(self, s).rstrip() for s in desc.split('\n') ] ) return wrapped fmt.format_description = decorate(fmt.format_description) 

This way you can get a help description that does the following:

 my_desc = """This is some text that wraps to some more stuff.\n \n And this is a new paragraph.\n \n This line comes before\n this line but not in a different paragraph.""" 

Works for me. :)

+1
source

For those of you who use user227667 but want to replace %prog in the epilogue, you can use:

 class MyParser(optparse.OptionParser): def format_epilog(self, formatter): return self.expand_prog_name(self.epilog) 

But in general, if possible, do not use optparse.

0
source

Source: https://habr.com/ru/post/887798/


All Articles