2012-05-29 29 views
1

我通過f2py在python中使用了一些fortran代碼。我想將fortran輸出重定向到一個我可以玩的變量。有這個問題,我發現有幫助。 Redirecting FORTRAN (called via F2PY) output in Python在Python中複製FORTRAN(通過F2PY調用)輸出

然而,我也想任選具有Fortran代碼寫入到終端以及記錄它。這可能嗎?

我有以下愚蠢的課,我從上面的問題拼湊在一起,也從 http://websrv.cs.umt.edu/isis/index.php/F2py_example

class captureTTY: 
    ''' 
    Class to capture the terminal content. It is necessary when you want to 
    grab the output from a module created using f2py. 
    ''' 
    def __init__(self, tmpFile = '/tmp/out.tmp.dat'): 
     ''' 
     Set everything up 
     ''' 
     self.tmpFile = tmpFile  
     self.ttyData = [] 
     self.outfile = False 
     self.save = False 
    def start(self): 
     ''' 
     Start grabbing TTY data. 
     ''' 
     # open outputfile 
     self.outfile = os.open(self.tmpFile, os.O_RDWR|os.O_CREAT) 
     # save the current file descriptor 
     self.save = os.dup(1) 
     # put outfile on 1 
     os.dup2(self.outfile, 1) 
     return 
    def stop(self): 
     ''' 
     Stop recording TTY data 
     ''' 
     if not self.save: 
      # Probably not started 
      return 
     # restore the standard output file descriptor 
     os.dup2(self.save, 1) 
     # parse temporary file 
     self.ttyData = open(self.tmpFile,).readlines() 
     # close the output file 
     os.close(self.outfile)   
     # delete temporary file 
     os.remove(self.tmpFile) 

我的代碼目前看起來是這樣的:

from fortranModule import fortFunction 
grabber = captureTTY() 
grabber.start() 
fortFunction() 
grabber.stop() 

我的想法是有所謂的沉默,我可以用它來檢查我是否允許顯示或不屬於Fortran輸出的標誌。這將被傳遞到captureTTY當我構建它,即

from fortranModule import fortFunction 
silent = False 
grabber = captureTTY(silent) 
grabber.start() 
fortFunction() 
grabber.stop() 

我真的不知道如何去實現這一點。最明顯的事情是:

from fortranModule import fortFunction 
silent = False 
grabber = captureTTY() 
grabber.start() 
fortFunction() 
grabber.stop() 
if not silent: 
    for i in grabber.ttyData: 
     print i 

我不是這一個大風扇,因爲我的FORTRAN方法需要很長的時間來運行,這將是很高興看到它在實時更新,而不僅僅是在結束。

任何想法?該代碼將運行在Linux機器上,而不是Windows上。我瀏覽過網頁,但還沒有找到解決方案。如果有的話,我相信它會很明顯!

乾杯,

ģ

澄清

從我認識到,上面沒有最清晰的評論。我目前擁有的是能夠記錄fortran方法的輸出。但是,這會阻止它打印到屏幕上。我可以將它打印到屏幕上,但不能記錄它。我想要選擇同時執行,即記錄輸出並使其實時打印到屏幕上。

就像旁邊一樣,Fortran代碼是一個擬合算法,我感興趣的實際輸出是每個迭代的參數。

+0

也許你不喜歡這個想法,但我通常所做的只是要求Fortran將輸出寫入頻繁刷新的日誌文件,然後讓python或其他腳本查看日誌。 – nye17

+1

fortran輸出是什麼樣的?它是一組數字嗎?如果是這樣,f2py應該能夠直接返回作爲一個numpy數組。 – mgilson

+0

@mgilson&nye17我已經澄清了這個問題,見上文。我想我的問題可能不是最清楚的。 – Ger

回答

0

你在Fortran子程序中試過類似這樣的東西嗎? (假設foo是要打印的東西,和52是你的日誌文件的單元號)

write(52,*) foo 
write(*,*) foo 

這應該打印foo到日誌文件,並在屏幕上。