我已经写了epytext到reST标记转换器,现在我想将我的整个库中的所有文档字符串从epytext转换为reST格式。替换python docstrings
是否有智能的方式来读取模块中的所有文档并写回替换?
ps:ast模块或许?
我已经写了epytext到reST标记转换器,现在我想将我的整个库中的所有文档字符串从epytext转换为reST格式。替换python docstrings
是否有智能的方式来读取模块中的所有文档并写回替换?
ps:ast模块或许?
也许最简单的做法就是用老式的方式做。这里有一些最初的代码让你去。这也许可能是更漂亮,但应该了解基本的概念:
def is_docstr_bound(line):
return "'''" in line or '"""' in line
# XXX: output using the same name to some other folder
output = open('output.py', 'w')
docstr_found = False
docstr = list()
with open('input.py') as f:
for line in f.readlines():
if docstr_found:
if is_docstr_bound(line):
# XXX: do conversion now
# ...
# and write to output
output.write(''.join(docstr))
output.write(line)
docstr = list()
docstr_found = False
else:
docstr.append(line)
else:
if is_docstr_bound(line):
docstr_found = True
output.write(line)
output.close()
,使之真正功能,你需要有一个文件搜索器和输出文件把它挂到其他目录。查看os.path模块以供参考。
我知道文档字符串绑定检查可能真的很弱。这可能是一个好主意(带状线,并检查它是否以文档字符串绑定开始或结束)。
希望能给出一些想法如何继续下去。也许有更好的方法来处理这个问题。 :)
我想知道内省和源处理的组合。下面是一些未经测试的伪代码:
import foo #where foo is your module
with open('foo.py',r) as f:
src = f.readlines()
for pything in dir(foo): #probably better ways to do this...
try:
docstring = pything.__doc__
except AttributeError:
#no docstring here
pass
#modify the docstring
new_docstring = my_format_changer(docstring)
#now replace it in the source
src = src.replace(docstring, new_docstring)
#When done, write it out
with open('new_foo.py','w') as fout:
fout.write(src)
显然你必须把一些小聪明在横穿模块查找具有文档字符串因此将递归对象的代码,但是这给你的总体思路。
这可能是一个矫枉过正的简单用法,但我会考虑使用2to3进行编辑。你只需要编写一个自定义修复程序。这不是很好的记载,但开发人员指南到Python 3.0:Python的2.6和迁移2到3:More about 2to3和Implement Custom Fixers给予足够的细节,上手...
epydoc的似乎包含一个to_rst()
方法可能有助于你实际上翻译了文档字符串。不知道它是否有什么好...
Pyment是一个工具,可以转换Python docstrings和创建缺少的骨架。它可以管理谷歌,epydoc的(javadoc的风格),Numpydoc,reStructuredText的(休息,狮身人面像默认值)文档字符串格式。
它接受单个文件或文件夹(也浏览子文件夹)。对于每个文件,它将识别每个文档字符串格式并将其转换为所需的格式。最后,将生成一个补丁以应用于该文件。
键入以下内容(可以使用的virtualenv):
$ git clone https://github.com/dadadel/pyment.git
$ cd pyment
$ python setup.py install
您可以通过执行转换您的项目,狮身人面像格式(REST),这是默认的输出格式,:
$ pyment /my/folder/project
散步槽我的目录结构和开/读/写文件,实在是微不足道。 我的问题是:是否有一种聪明的方式来读取模块中的所有文档并写回替代品? 这不能用像正则表达式这样的机制(像re.finditer('\“\”\“(。*)\”\“\”',source))那样天真地做,因为我不想搞乱剩下的代码。 – tomaz 2010-03-19 17:23:32
我发现了一个类似的问题,您可能会感兴趣。请参阅http://stackoverflow.com/questions/768634/python-parse-a-py-file-read-the-ast-modify-it-then-write-back-the-modified。 – 2010-03-19 17:34:18
Docstrings不需要有三重引号的字符串,并且不是所有用三引号字符串引用的都是一个文档字符串,所以这只适用于python文档字符串的一个子集。 – jcdyer 2010-03-19 19:17:00