How to insert newlines on argparse help text?
Utilize RawTextHelpFormatter
while setting up your argparse.ArgumentParser
to include newlines (\n
) in your help text:
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:
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:
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:
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!
Was this article helpful?