开发者

Redirect python interactive help()

开发者 https://www.devze.com 2023-02-04 21:49 出处:网络
I\'m working on a interactive python shell for an application using Qt.However I can\'t seem to get the interactive help to redirect.I have this in my python code:

I'm working on a interactive python shell for an application using Qt. However I can't seem to get the interactive help to redirect. I have this in my python code:

class OutputCatcher:
    def __init__(self):
        self.data = ''
    def write(self, stuff):
        self.data += stuff

sys.stdout = OutputCatcher()

However when ever I run help() it doesn't redirect the interact开发者_如何转开发ive help, it just dumps it out to the console where I ran the python script from. If I press ctrl+c in the console it then sends it to my OutputCatcher object.

I did try google but couldn't really find anything.


There's no need to guess what help is doing, just read the source.

The help builtin is create in site.py, it's an instance of class _Helper. When called it simply delegates the call through to pydoc.help(...) the source for which you'll find in pydoc.py.

class _Helper(object):
    """Define the built-in 'help'.
    This is a wrapper around pydoc.help (with a twist).

    """

    def __repr__(self):
        return "Type help() for interactive help, " \
               "or help(object) for help about object."
    def __call__(self, *args, **kwds):
        import pydoc
        return pydoc.help(*args, **kwds)

pydoc.help is an instance of pydoc.Helper with input/output set to sys.stdin, sys.stdout, but (and I suspect this is where you have your problem) it uses the value of stdin/stdout at the time when pydoc is imported so later rebinding them won't have any effect.

I suggest you replace the builtin help instance with your own _Helper class that creates a fresh pydoc Helper explicitly with whatever files you need.


Help doesn't just dump to stdout, but interacts with the terminal. It also is never meant to be used outside of the shell, so it wouldn't be written to guarantee such things work.

What you are trying to do is implement a terminal and that is a non-trivial task, but there are probably existing terminal emulation libraries for Qt. Possibly even written in Python and surely with bindings.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号