【问题标题】:How to open online reference from IPython?如何从 IPython 打开在线参考?
【发布时间】:2019-10-21 16:56:25
【问题描述】:

有没有办法让 IPython 打开指向相应在线参考的浏览器?

尤其是numpy,scipy,matplotlib?

例如,numpy.linalg.cholesky 的文档很难在终端中阅读。

【问题讨论】:

    标签: numpy ipython


    【解决方案1】:

    我认为没有直接的方法可以让 IPython 或任何 shell 在线打开文档,因为 shell 的主要工作是让您与它们作为 shell 的对象进行交互。

    但是,我们可以编写一个脚本来在浏览器上打开一个带有文档的新选项卡。像这样:

    import webbrowser
    
    docsList = {
        "numpy" : lambda x: "https://docs.scipy.org/doc/numpy/reference/generated/" + x + ".html",
        "scipy" : lambda x: "https://docs.scipy.org/doc/scipy/reference/generated/" + x + ".html",
        "matplotlib" : lambda x: "https://matplotlib.org/api/" + x.split('.')[1] + "_api.html",
        "default" : lambda x: "https://www.google.com/search?q=documentation+" + x
        }
    
    def online(method_name):
        """
        Opens up the documentation for method_name on the default browser.
        If the package doesn't match any entry in the dictionary, falls back to
        Google.
    
        Usage
        -------
        >>> lookUp.online("numpy.linalg.cholesky")
        >>> lookUp.online("matplotlib.contour")
        """
        try:
            url = make_url(method_name)
        except AttributeError:
            print("Enter the method name as a string and try again")
            return
    
        webbrowser.open(url, new = 2)
        return
    
    
    def make_url(method_name):
        package_name = method_name.split('.')[0]
        try:
            return docsList[package_name](method_name)
        except KeyError:
            return docsList["default"](method_name)
    

    您可以将上面的内容保存为“lookUp.py”,放在 Python 可以找到的位置,然后在需要时将其导入。

    注意事项:

    这个方法接受字符串作为输入,所以如果你在一个函数上调用它会抛出一个错误。

    >>> lookUp.online("numpy.linalg.cholesky")
    

    会起作用的。

    >>> lookUp.online(numpy.linalg.cholesky)
    

    会要求您将其作为字符串提供。 因此,请使用自动完成功能来获取该功能,然后将其用引号括起来以使其工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多