如何为f2py文档化fortran函数?
我想用文档字符串(docstring)或者类似的东西来记录我的Fortran程序,这样在使用Python的帮助命令时也能看到这些文档。f2py自动生成的文档字符串不够详细,我需要添加更多信息,就像我们在Python函数中写文档字符串那样。
我想要的效果应该是这样的:
mymod.f :
subroutine foo()
! This is my function
end subroutine
然后在Python会话中:
>>> import mymod
>>> help(mymod.foo)
1 个回答
3
一种比较简单的方法是把文档保存成ascii文件,然后在运行时加载它们。f2py的文档在编译时就已经写死了,目前还没有办法在包装器中修改它(如果能改就好了!)。
比如,你可以写一个__init__.py文件,这个文件会加载编译好的f2py模块_mymodule.so,并且可以覆盖或添加f2py的__doc__字符串。这样在ipython中输入">> mymodule.function?"就能正常工作,但奇怪的是输入">> help(mymodule.function)"却不行!我也不知道为什么…
下面这个__init__.py的代码片段会从doc/文件夹中加载文档,并且读取与每个函数相关的doc/"函数名".doc文件。在这种情况下,文档总是会被加载,但你也可以选择手动加载。
def load_documentation():
"""
Fills the modules __doc__ strings
"""
import os
from . import _mymodule
print('loading documentation')
docfolder = os.path.abspath(os.path.join(os.path.dirname(__file__), 'doc'))
for name,func in _mymodule.__dict__.items():
if callable(func):
try:
path = os.path.join(docfolder,name.lower()+'.doc')
docfile = open(path)
doc = docfile.read()
docfile.close()
func.__doc__ = doc
except IOError as msg:
print(msg)
load_documentation()
from _mymodule import *