我用 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
通过这种方式,处理后的代码可以被 autodoc 读取,但仍然具有我真正需要的文档字符串。这是解决此问题的最佳方法吗?有人对如何编写转换代码的小程序有任何建议吗?
我可以使用一些正则表达式非常轻松地消除元类问题,但我正在努力解决其余问题。
m = re.search("\(metaclass=.*\)", file_content)
if m:
file_content = "".join(file_content[:m.start()], file_content[m.end():])
ast 模块有用吗?
谢谢。
最佳答案
您可以直接安装sphinx的开发版本,它支持python 3。
pip-3.2 install hg+https://bitbucket.org/birkenfeld/sphinx
我在您的类(class)上测试了自动文档功能,它有效。
关于python - 将Python 3转换为autodoc可以读取的 "simple"python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5605851/