我通过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代码是一个拟合算法,我感兴趣的实际输出是每个迭代的参数。
也许你不喜欢这个想法,但我通常所做的只是要求Fortran将输出写入频繁刷新的日志文件,然后让python或其他脚本查看日志。 – nye17
fortran输出是什么样的?它是一组数字吗?如果是这样,f2py应该能够直接返回作为一个numpy数组。 – mgilson
@mgilson&nye17我已经澄清了这个问题,见上文。我想我的问题可能不是最清楚的。 – Ger