繁体   English   中英

python和f2py错误-NameError:未定义全局名称“ inputUtil”

[英]python and f2py error - NameError: global name 'inputUtil" is not defined

我已经使用f2py(inputUtil.pyd)在python中编译了一个fortran代码。 我将此函数导入到我的主要python代码中,并从字符串向该函数传递两个字符(locationAID和locationBID)。

这是错误消息:

>>> 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)
...

这是我使用f2py转换为python的fortran代码的一部分,该代码显示了传递给此函数的字符:

     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的老程序员(从打孔卡的那天开始!)。 因此,请以老人可以跟随的方式回应。

谢谢你的帮助。

拳爸爸

我认为您在这里混淆了功能和模块。 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另一个文件use inpututils例程顶部的use inpututils模块中的use inpututils导入模块中的所有子例程(在implicit none之前)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM