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