Search code examples
pythonargparse

When I use redirect_stdout in python 3.11, the terminal width appears to be set to 80. How can I change this value?


For example, when automatically collating arparse help, I'd ideally like to set a specific width:

def parse_help(command_list=... width=168):
    command_list = [] if command_list is ... else command_list

    s = io.StringIO()
    with redirect_stdout(s, width=width):
        try:
            do_command([*command_list, '--help'])
        except SystemExit:
            pass

    help_text = s.getvalue()
    print_help(help_text)

    for subcommand in get_subcommands(help_text):
        parse_help([*command_list, subcommand])

Solution

  • argparse's help formatter uses shutil.get_terminal_size to obtain the column size of the terminal connected to stdout, which falls back to 80 characters when stdout is not connected to a terminal.

    To override it for child processes that use argparse to produce help messages, one easy approach is to set the environment variable COLUMNS as mentioned in the documentation of shutil.get_terminal_size:

    import os
    
    os.environ['COLUMNS'] = '168'
    s = io.StringIO()
    with redirect_stdout(s):
        do_command([*command_list, '--help'])
    

    Demo: https://replit.com/@blhsing1/DemandingPoliticalConversion