I have a written a program in Python 3 and are using Sphinx to document it. Sphinx's autodoc is great, however it only works with Python 2. Some modules work fine in autodoc, however modules don't. Some examples: Python 2 complains about Python 3 style metaclasses, and some modules which do开发者_StackOverflow中文版n't exist anymore in Python 2 such as configparser. This is annoying as it cannot import the docstrings from that file.
I don't want to rewrite the whole program in Python 2, however I want to use autodoc.
One idea I had was a small program that read each Python file and removed all functionality but just left the basic function and classes with their docstrings (because autodoc imports each module and reads the docstring of a specific function or class).
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")
into...
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
In this way the processed code can be read by autodoc, but still have the docstrings which is what I really need. Is this the best way of going about this, and does anyone have any suggestions as to how to write the little program which converts the code.
I can remove the metaclass problem very easily with some regular expressions, but I am struggling with the rest.
m = re.search("\(metaclass=.*\)", file_content)
if m:
file_content = "".join(file_content[:m.start()], file_content[m.end():])
Would the ast module be useful?
Thanks.
You can just install the development version of sphinx, which supports python 3.
pip-3.2 install hg+https://bitbucket.org/birkenfeld/sphinx
I tested the autodoc feature on your class and it worked.
What tends to be the solution is sprinkling try/except clauses in your code.
Python 2.6 has configparser but it is known as ConfigParser (python 3 changed the camelcase names to all lower case)
so something like:
try:
import configparser
except ImportError:
#we are in 2.x
import ConfigParser as configparser
you might want to do a few things like this where it's broken. between the two. metaclasses though between the two I'm not sure to handle.
There's a 3to2 library that can convert Python 3 code to python 2. You could try this in conjunction with Sphinx.
精彩评论