V
V
Vladimir2018-03-03 22:45:05
Python
Vladimir, 2018-03-03 22:45:05

Python - How to get help() text into a variable?

How to get text into variable a ?
import random
a= help(random.sample)
print(a) # - now None

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-03-03
@PolkovnikZ

a = random.sample.__doc__
I was curious about how to intercept the output, and I found a solution:

from io import StringIO
import random
import sys

class OutputInterceptor(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self

    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        del self._stringio
        sys.stdout = self._stdout

with OutputInterceptor() as output:
    help(random.sample)

print('\n'.join(output))

V
Vladimir, 2018-03-04
@PolkovnikZ

Bravo!!!! I suspected that this can be done in python -c connecting sys :-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question