2013-04-10 150 views
0

我已经使用f2py(inputUtil.pyd)在python中编译了fortran代码,我将此函数导入到我的主python代码中,并将两个字符传递给此从一个字符串函数(locationAID和locationBID)python和f2py错误 - NameError:全局名称'inputUtil'未定义

以下是错误消息:

>>> Traceback (most recent call last): 
    File "C:\FROM_OLD_HD\SynBio\Contact 5-23-12\contactsource_workingcopy\python\main.py", line 234, in batchExecute 
    self.prepareProteins(tempList[1].replace("protA: ",""),tempList[2].replace("protAID: ",""),tempList[3].replace("protB: ",""),tempList[4].replace("protBID: ","")) 
    File "C:\FROM_OLD_HD\SynBio\Contact 5-23-12\contactsource_workingcopy\python\main.py", line 668, in prepareProteins 
    total = inputUtil(locationAID,locationBID) 
NameError: global name 'inputUtil' is not defined 

这里是我的主要Python代码部分:

#import fortran modules 
from contact import * 
from inputUtil import * 

.... 
def prepareProteins(self, locationA, locationAID, locationB, locationBID): 
    self.output("Generating temporary protein files...") 
    start_time = time.time() 

    shutil.copyfile(locationA,"."+os.sep+"prota.pdb") 
    shutil.copyfile(locationB,"."+os.sep+"protb.pdb") 


    total = inputUtil(locationAID,locationBID) 
... 

这里是部分FO rtran代码,我使用转换f2py显示的字符传递给该函数的Python:

 subroutine inputUtil(chida,chidb) 
c 
     integer resnr,nbar,ljnbar,ljrsnr 
     integer resns,nbars 
     integer resnc,nbarc 
     integer resnn,nbarn 
c 
     integer numa,numb,ns,n 
c 
     character*6 card,cards,cardc,cardn,ljcard 
c 
     character*1 alt,ljalt,chid,ljchid,code,ljcode 
     character*1 alts,chids,codes 
     character*1 altc,chidc,codec 
     character*1 altn,chidn,coden 
     character*1 chida,chidb 
.... 

f2py伟大的工作,所以我不认为这是问题。我只是在学python - 我是一个旧时代的Fortran程序员(从打卡当天开始!)。所以,请回复一个老人可以遵循的东西。

感谢您的任何帮助。

PunchDaddy

回答

1

我认为你在这里混淆的功能和模块。当你做from inputUtil import *然后调用inputUtil时,这与调用函数inputUtil.inputUtil相同。

我在你提供的Fortran代码上运行了f2py,还有一行:print*, "hello from fortran!"。我也不得不删除C条评论,据推测,因为我用了.f90。这里是我使用的命令:

python "c:\python27\scripts\f2py.py" -c --fcompiler=gnu95 --compiler=mingw32 -lmsvcr71 -m inputUtil inputUtil.f90 

现在我应该得到一个名为inputUtil的python模块。让我们试试。简单的Python:

import inputUtil 
inputUtil.inputUtil('A', 'B') 

由此我得到:

AttributeError: 'module' object has no attribute 'inputUtil' 

那么这是怎么回事?让我们来看看模块:

print dir(inputUtil) 

这将返回:

['__doc__', '__file__', '__name__', '__package__', '__version__', 'inpututil'] 

显然,在inputUtil的大写的U已经转换为小写。让我们来调用该函数的名称以小写:

inputUtil.inpututil('A', 'B') 

现在它打印:

hello from fortran! 

成功!

看起来它可能是f2py的一个问题/功能,将函数名称转换为小写。由于我一般都使用小写字母,所以我从未遇到过。

为了将来的参考,我还建议将Fortran放在一个模块中,并将intent语句添加到您的子例程参数中。这将使得在f2py模块和Python之间传递变量更容易。裹在一个模块中,像这样:

module inpututils 

contains 

subroutine foo(a, b) 
...code here... 
end subroutine 

end module 

然后你导入所有子程序从模块use inpututils在子程序的顶部在另一个文件(implicit none之前)。

+0

很好 - 非常感谢您的帮助! – pete 2013-04-15 14:30:16

+0

没问题!如果解决了您的问题,请考虑接受答案(点击向下箭头旁边的勾号)。 – bananafish 2013-04-15 21:32:48

相关问题