重定向python交互式帮助() [英] Redirect python interactive help()

查看:62
本文介绍了重定向python交互式帮助()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为使用 Qt 的应用程序开发交互式 python shell.但是我似乎无法获得重定向的交互式帮助.我的python代码中有这个:

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()

但是,当我运行 help() 时,它不会重定向交互式帮助,它只是将其转储到我运行 python 脚本的控制台.如果我在控制台中按 ctrl+c,它会将它发送到我的 OutputCatcher 对象.

However when ever I run help() it doesn't redirect the interactive 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.

help 内置是在 site.py 中创建的,它是 _Helper 类的一个实例.当被调用时,它只是将调用委托给 pydoc.help(...) ,你可以在 pydoc.py 中找到它的源代码.

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 是 pydoc.Helper 的一个实例,输入/输出设置为 sys.stdinsys.stdout,但是(我怀疑这是您遇到问题的地方)它在导入 pydoc 时使用 stdin/stdout 的值,因此以后重新绑定它们不会产生任何影响.

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.

我建议你用你自己的 _Helper 类替换内置的帮助实例,该类使用你需要的任何文件显式创建一个新的 pydoc Helper.

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.

这篇关于重定向python交互式帮助()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆