在Python中复制FORTRAN(通过F2PY调用)输出

2024-05-19 03:38:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过f2py在python中使用一些fortran代码。用forti将输出重定向到可以播放的变量。有一个问题我觉得很有帮助。 Redirecting FORTRAN (called via F2PY) output in Python

不过,我也希望有选择地将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)

我的代码当前如下所示:

^{pr2}$

我的想法是使用一个名为silent的标志来检查是否允许显示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&Mac机器上运行,而不是windows。我浏览了一下网络,但没有找到解决办法。如果真的有,我相信这将是痛苦显而易见的!在

干杯

G

澄清:

从这些评论中我意识到,上面的内容并不是最清楚的。我目前拥有的是记录fortran方法的输出的能力。但是,这会阻止它打印到屏幕上。我可以把它打印到屏幕上,但不能记录下来。我想选择同时进行两个操作,即记录输出并实时打印到屏幕上。在

顺便说一句,fortran代码是一个合适的算法,我感兴趣的实际输出是每次迭代的参数。在


Tags: the代码selffalseoutputossaveoutfile
1条回答
网友
1楼 · 发布于 2024-05-19 03:38:13

你在Fortran子程序中尝试过类似的方法吗?(假设foo是您要打印的内容,52是日志文件的单元号)

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

这应该将foo打印到日志文件和屏幕上。在

相关问题 更多 >

    热门问题