2

我用 Python 3 编写了一个程序,并正在使用 Sphinx 来记录它。Sphinx 的 autodoc 很棒,但它只适用于 Python 2。一些模块在 autodoc 中可以正常工作,但模块不能。一些例子:Python 2 抱怨 Python 3 风格的元类,以及一些在 Python 2 中不再存在的模块,例如configparser。这很烦人,因为它无法从该文件导入文档字符串。

我不想用 Python 2 重写整个程序,但是我想使用 autodoc。

我的一个想法是一个小程序,它读取每个 Python 文件并删除所有功能,但只留下基本函数和类及其文档字符串(因为 autodoc 导入每个模块并读取特定函数或类的文档字符串)。

import configparser
import os

class TestClass:
    """
    I am a class docstring.
    """
    def method(self, argument):
        """
        I am a method docstring.
        """
        #Some code here
        print(os.getcwd())

def TestFunction():
    """
    I am a function docstring.
    """
    #Some more useless code here
    return os.path.join("foo", "bar")

进入...

class TestClass:
    """
    I am a class docstring.
    """
    def method(self, argument):
        """
        I am a method docstring.
        """
        pass

def TestFunction():
    """
    I am a function docstring.
    """
    pass

通过这种方式,自动文档可以读取处理后的代码,但仍然具有我真正需要的文档字符串。这是解决这个问题的最佳方法吗?有人对如何编写转换代码的小程序有任何建议吗?

我可以用一些正则表达式很容易地消除元类问题,但我正在努力解决剩下的问题。

m = re.search("\(metaclass=.*\)", file_content)
if m:
    file_content = "".join(file_content[:m.start()], file_content[m.end():])

ast模块有用吗?

谢谢。

4

3 回答 3

5

您可以只安装支持 python 3 的 sphinx 的开发版本。

pip-3.2 install hg+https://bitbucket.org/birkenfeld/sphinx

我在您的课堂上测试了自动文档功能并且它有效。

于 2011-04-11T20:25:54.073 回答
1

解决方案往往是在代码中添加 try/except 子句。

Python 2.6 有 configparser,但它被称为 ConfigParser(python 3 将驼峰名称更改为全部小写)

所以像:

try:
  import configparser
except ImportError:
  #we are in 2.x
  import ConfigParser as configparser

你可能想在它坏了的地方做一些这样的事情。两者之间。虽然我不确定两者之间的元类。

于 2011-04-09T16:30:39.720 回答
0

有一个3to2 库可以将 Python 3 代码转换为 python 2。您可以将其与 Sphinx 结合使用。

于 2011-04-09T16:53:51.303 回答