Pybites Logo

Capture stdout

Level: Intermediate (score: 3)

Sometimes you need to capture stdout in your script. Python makes it easy with contextlib's redirect_stdout.

In this Bite you will use it to get the length of a help text as returned by help.

Complete get_len_help_text which receives a builtin. Run help against this builtin and capture its output in a variable and return its length (number of chars). If a non-builtin is passed into the function, raise a ValueError (hint: you can use BuiltinFunctionType to check this).

Here you see the function in action:

>>> from helplen import get_len_help_text
>>> get_len_help_text(max)
402
>>> get_len_help_text(pow)
278
>>> get_len_help_text('bogus')
...
ValueError

Good luck and keep calm and code in Python!