我用 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模块有用吗?
谢谢。