Explain Codes LogoExplain Codes Logo

How to insert newlines on argparse help text?

python
prompt-engineering
argparse
custom-formatter
Alex KataevbyAlex Kataev·Jan 5, 2025
TLDR

Utilize RawTextHelpFormatter while setting up your argparse.ArgumentParser to include newlines (\n) in your help text:

import argparse # Initialize with RawTextHelpFormatter parser = argparse.ArgumentParser(description="Add newlines", formatter_class=argparse.RawTextHelpFormatter) # Add argument with newlines in the help text parser.add_argument('--option', type=int, help='Say hi to line 1\nHello, line 2\nHey there, line 3') args = parser.parse_args()

Run the script with --help to witness the magic of newlines in your help message.

Custom formatter for selective formatting

Sometimes, we might want to use newlines sparingly, not in every piece of text. To achieve this, we can create a SmartFormatter. This guy is smart enough to preserve newlines only where it's important:

import argparse class SmartFormatter(argparse.HelpFormatter): def _split_lines(self, text, width): if text.startswith('R|'): return text[2:].splitlines() # keeping the newlines in check return super()._split_lines(text, width) parser = argparse.ArgumentParser(description='Your description', formatter_class=SmartFormatter) parser.add_argument('--option', help='R|Line 1 gets a newline\nAnd so does Line 2\nBut others won\'t') args = parser.parse_args()

There's an even smarter SmartFormatter on Bitbucket offering this and more, like adding defaults while not messing with any other formatting. Isn't that smart?

Tabulated and readable

For special cases where you need to retain tabs and newlines, use textwrap.dedent. This allows you to remove common leading whitespace from each line in input and keep everything clean:

import argparse import textwrap class MultilineFormatter(argparse.HelpFormatter): def _fill_text(self, text, width, indent): text = textwrap.dedent(text).strip() return ''.join(indent + line for line in textwrap.wrap(text, width)) parser = argparse.ArgumentParser(description='Multiline Help', formatter_class=MultilineFormatter) parser.add_argument('--list', type=str, help=textwrap.indent(textwrap.dedent("""\ - One line at a time - Unlimited power - The clean look of multiline help """), " ")) args = parser.parse_args()

This way every line of argument in your help descriptor maintains its dignity.

Control your text

Use a simple one-liner custom formatter to preserve your original text's formatting:

import argparse class PreserveNewlineFormatter(argparse.HelpFormatter): def _split_lines(self, text, width): return text.splitlines() # split and wrap each line separately parser = argparse.ArgumentParser(description="Preserve Newlines", formatter_class=PreserveNewlineFormatter) parser.add_argument('--manual', help='Line 1\nLine 2\nSuper neat, right?') args = parser.parse_args()

This custom formatter keeps each line formatted and wrapped individually.

Nuances and potential issues

Subclassing formatters isn't just for looking cool. It can also be a massive help when your command involves multi-line block quotes or code samples.

However, beware the edge cases. Extremely long lines can make your help text look like an unreadable mess due to terminal width restrictions. So always test your script on different terminal sizes to prevent your careful formatting from becoming a laughing stock!