3

我正在寻找一种通过广泛使用 help() 来简化进入新模块的方法。

我目前遇到的问题是输出非常有用,但很难在交互式解释器中滚动。我正在寻找的是一种探索 python 模块的方式,这种方式类似于 R 处理文档的方式(使用 R PRoject 时)。

R 输出单个 HTML 文件,允许您滚动浏览参数、函数;我在 Windows 上使用 python 2.7。

我找到了 pydoc,它准确地输出了我在控制台中寻找的内容,但我不完全确定如何从记录所有已安装包的“网络服务器”转移到仅提供和打开一个html 页面,一旦我输入 help(x),输出它通常会在解释器中输出的内容。

任何帮助是极大的赞赏。

4

3 回答 3

3

我编写了一个简短的函数,它接受一个包含模块名称的字符串,该字符串使用 pydoc 创建一个 html 文件并显示在您的默认浏览器中。

它不设置网络服务器,而只是将文件加载到网络浏览器中。

import subprocess
import os
import tempfile
import sys
import time

def show_help(module):
    """ Create and show HTML page of module documentation 

        Pass module as a string
    """

    # Create temporary directory to store documentation in
    with tempfile.TemporaryDirectory() as temp_folder:
        orignal_cwd = os.getcwd()

        # Change working directory to temporary folder
        os.chdir(temp_folder)

        # Create HTML page of doc
        subprocess.call(["pydoc", "-w", module], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)       

        filepath = os.path.join(temp_folder, module + ".html")

        # Reset working directory
        os.chdir(orignal_cwd)

        # Open default program to view HTML files
        if sys.platform.startswith('darwin'):
            subprocess.call(('open', filepath), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        elif os.name == 'nt':
            os.startfile(filepath)
        elif os.name == 'posix':
            subprocess.call(('xdg-open', filepath), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

        # Sleep for 2 seconds so browser can open before deleting file
        time.sleep(2)

我已经在 linux 上使用 python3.4 对其进行了测试,它可以正常工作,但我没有在 Windows 上对其进行检查。

您可以在解释器中将其作为模块导入,然后仅用于show_help("module name")查看文档,其中“模块名称”是模块名称作为字符串。比如show_help("os")

于 2014-12-20T21:53:03.333 回答
1

您可以使用pydoc.render_doc创建html文件。

import pydoc
str_help = pydoc.render_doc(str)
with open("str_doc.html", "w") as doc_file:
    doc_file.write(str_help)

然后你可以在网络浏览器中打开这个文件:

import webbrowser
webbrowser.open("file:///path/to/your/doc_file.html")
于 2014-12-29T10:36:53.477 回答
0

感谢您的回答。我的最终解决方案是结合您的两种方法:

  • 我如上所述导入了 TemporaryDirectory();
  • 然后我调用 pydoc.writedoc(x) 在临时文件中生成一个 html 文件。文件夹;
  • 我使用不同的代码段来禁止从 pydoc 打印“wrote x.html”;
  • 我使用 webbrowser.open_new(url) 在我的默认浏览器中打开一个新页面。

现在调用 help(os) 会生成一个临时 HTML 文件(在 pydoc 中)并在我的标准浏览器中打开它;这正是我所需要的。

from __future__ import print_function

import pydoc
import os
import sys
import time
import webbrowser

import warnings as _warnings
import os as _os

from tempfile import mkdtemp
from contextlib import contextmanager


@contextmanager
def suppress_stdout():
    """ Suppresses output of all functions called as follows:
    with suppress_stdout():
        functioncall()
    source: http://thesmithfam.org/blog/2012/10/25/temporarily-suppress-console-output-in-python/
    """
    with open(os.devnull, "w") as devnull:
        old_stdout = sys.stdout
        sys.stdout = devnull
        try:
            yield
        finally:
            sys.stdout = old_stdout


class TemporaryDirectory(object):
    """Create and return a temporary directory.  This has the same
    behavior as mkdtemp but can be used as a context manager.  For
    example:

        with TemporaryDirectory() as tmpdir:
            ...

    Upon exiting the context, the directory and everything contained
    in it are removed.
    """

    def __init__(self, suffix="", prefix="tmp", dir=None):
        self._closed = False
        self.name = None # Handle mkdtemp raising an exception
        self.name = mkdtemp(suffix, prefix, dir)

    def __repr__(self):
        return "<{} {!r}>".format(self.__class__.__name__, self.name)

    def __enter__(self):
        return self.name

    def cleanup(self, _warn=False):
        if self.name and not self._closed:
            try:
                self._rmtree(self.name)
            except (TypeError, AttributeError) as ex:
                # Issue #10188: Emit a warning on stderr
                # if the directory could not be cleaned
                # up due to missing globals
                if "None" not in str(ex):
                    raise
                print("ERROR: {!r} while cleaning up {!r}".format(ex, self,),
                      file=_sys.stderr)
                return
            self._closed = True
            if _warn:
                self._warn("Implicitly cleaning up {!r}".format(self),
                           ResourceWarning)

    def __exit__(self, exc, value, tb):
        self.cleanup()

    def __del__(self):
        # Issue a ResourceWarning if implicit cleanup needed
        self.cleanup(_warn=True)

    # XXX (ncoghlan): The following code attempts to make
    # this class tolerant of the module nulling out process
    # that happens during CPython interpreter shutdown
    # Alas, it doesn't actually manage it. See issue #10188
    _listdir = staticmethod(_os.listdir)
    _path_join = staticmethod(_os.path.join)
    _isdir = staticmethod(_os.path.isdir)
    _islink = staticmethod(_os.path.islink)
    _remove = staticmethod(_os.remove)
    _rmdir = staticmethod(_os.rmdir)
    _warn = _warnings.warn

    def _rmtree(self, path):
        # Essentially a stripped down version of shutil.rmtree.  We can't
        # use globals because they may be None'ed out at shutdown.
        for name in self._listdir(path):
            fullname = self._path_join(path, name)
            try:
                isdir = self._isdir(fullname) and not self._islink(fullname)
            except OSError:
                isdir = False
            if isdir:
                self._rmtree(fullname)
            else:
                try:
                    self._remove(fullname)
                except OSError:
                    pass
        try:
            self._rmdir(path)
        except OSError:
            pass


def help(thing):
    """ Create and show HTML page of module documentation,
    It should accept anything that the regular help() accepts.
    """

    # Create temporary directory to store documentation in
    with TemporaryDirectory() as temp_folder:
        orignal_cwd = os.getcwd()

        # Change working directory to temporary folder
        os.chdir(temp_folder)

        # Create HTML page of doc
        object, name = pydoc.resolve(thing)
        pydoc.writedoc(thing)
        with suppress_stdout():
            filepath = os.path.join(temp_folder, name + ".html")

        # Reset working directory
        os.chdir(orignal_cwd)

        # Open default program to view HTML files
        webbrowser.open_new(filepath)

        # Sleep for 2 seconds so browser can open before deleting file
        time.sleep(2)

if __name__ == "__main__":
    help(os)
于 2014-12-31T14:51:57.080 回答