Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect all out from argparse to a socket connection but not stdout in general

I'm trying to figure out how to redirect/catch (in a string) all output from argparse.parse_args() to a upd-socket (server), but not from stdout in general.

Eg when running this code:

import argparse

parser = argparse.ArgumentParser(prog='PROG')

parser.add_argument('-x', nargs=2)

parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))

args = parser.parse_args('-x p g -h'.split())
like image 810
RePsEj Avatar asked Jan 23 '26 00:01

RePsEj


1 Answers

With Python 3.4+, you can use redirect_stdout from contextlib

Here's an example program demonstrating this capture/redirection

#!/usr/bin/env python3
import argparse
import io
from contextlib import redirect_stdout


def argparser(args_external=None):
    parser = argparse.ArgumentParser(description="an example program")
    parser.add_argument(
        "-v", "--verbose", action="store_true",
        help="Enable verbose output")
    arguments = parser.parse_args(args_external)  # None -> sys.argv

    # this string goes to stdout, but is captured by redirect_stdout
    print("verbose=={}".format(arguments.verbose))

    return arguments


def main():
    f = io.StringIO()
    with redirect_stdout(f):
        argparser()
    s = f.getvalue()

    print("this statement occurs after the argparser runs")
    print("string contents from argparser: {}".format(s))


if __name__ == "__main__":
    main()

output

% python3 example.py -v
this statement occurs after the argparser runs
string contents from argparser: verbose==True

Additionally, ArgumentParser().parse_args() will accept a list (defaults to sys.argv) if you want to call the argparser multiple times

like image 161
ti7 Avatar answered Jan 25 '26 08:01

ti7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!