Tips and Tricks - standard library

Capture Output (Permalink)

There are different built-in as well as third-party functions, which print their output directly to stdout. Suppose you want to capture the result of calling the built-in help() function and process it further. To achieve that, you can utilise the redirect_stdout() function from the contextlib standard library.

For example, you can use a io.StringIO object as the container for the result in combination with contextlib.redirect_stdout(), which directs it to the io.StringIO object:

import contextlib
import io

output_stream = io.StringIO()
with contextlib.redirect_stdout(output_stream):
    help(pow)

output_stream = output_stream.getvalue()
print("value:", output_stream)

An alternative is to provide a file handle to the contextlib.redirect_stdout() function to direct the output to a file:

import contextlib

with open("help.txt", "w") as f:
    with contextlib.redirect_stdout(f):
        help(pow)

Last but not least, you can also direct it to stderr as follows:

import contextlib
import sys

with contextlib.redirect_stdout(sys.stderr):
    help(pow)

Argparse: Convert Input to Absolute Path (Permalink)

Suppose you created a command-line interface using Python's argparse module and want to convert incoming paths directly to absolute ones. Thanks to the nature of argparse, this is pretty easy!

When adding a new argument to an ArgumentParser, you can specify the type of the argument. To convert the input to a regular pathlib.Path object, simply provide pathlib.Path to the type parameter:

import argparse
import pathlib

parser = argparse.ArgumentParser(description="Simple Parser")
parser.add_argument(
    dest="path",
    type=pathlib.Path,
)

Fortunately, you can supply any callable to the type parameter. To convert the supplied path to an absolute one, simply use a lambda-function:

import argparse
import pathlib

parser = argparse.ArgumentParser(description="Simple Parser")
parser.add_argument(
    dest="path",
    type=lambda p: pathlib.Path(p).absolute(),
)