2013-04-10 113 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

相關問題