本文介绍了用Python重定向FORTRAN(通过F2PY调用)输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我试图弄清楚如何通过使用F2PY来重定向来自一些FORTRAN代码的输出,这些FORTRAN代码已经为其生成了一个Python接口。我试过了:

  from fortran_code import fortran_function 
stdout_holder = sys.stdout
stderr_holder = sys。 stderr
sys.stdout = file(/ dev / null,w)
fortran_function()
sys.stdout.close()
sys.stderr.close )
sys.stdout = stdout_holder
sys.stderr = stderr_holder

这是在Python中重定向输出的事实上的方法,但它在这种情况下似乎不起作用(即无论如何显示输出)。

我找到了说:这是可能的阅读来自pts设备的消息,例如ttysnoop这样做。有关ttysnoop的信息似乎很难在网上找到(我不认为它已在几年内更新;例如,只与tarballs,RPMs和.deb有联系),收到响应没有运气,它需要一些我无法创建的linux特定的utmp功能。



我对任何有关如何重定向输出的建议都开放了(它不必使用ttysnoop)。

感谢!

解决方案
标准输出和标准输出fds被C共享库继承。

  from fortran_code import fortran_function 
import os

print将运行fortran函数!

#打开2 fds
null_fds = [os.open(os.devnull,os.O_RDWR)for x in xrange(2)]
#将当前文件描述符保存为一个元组
save = os.dup(1),os.dup(2)
#把/ dev / null fds放在1和2
os.dup2(null_fds [0],1 )
os.dup2(null_fds [1],2)

#***运行函数***
fortran_function()

#恢复文件描述符,以便我可以打印结果
os.dup2(save [0],1)
os.dup2(save [1],2)
#关闭临时fds
os.close(null_fds [0])
os.close(null_fds [1])$ ​​b
$ b printdone!


I'm trying to figure out how to redirect output from some FORTRAN code for which I've generated a Python interface by using F2PY. I've tried:

from fortran_code import fortran_function
stdout_holder = sys.stdout
stderr_holder = sys.stderr
sys.stdout = file("/dev/null","w")
fortran_function()
sys.stdout.close()
sys.stderr.close()
sys.stdout = stdout_holder
sys.stderr = stderr_holder

This is the de facto method of redirecting output in Python, but it doesn't seem to work in this case (i.e., the output is displayed anyway).

I did find a mailing list post from 2002 saying that "It is possible to read messages from pts devices, e.g. ttysnoop does this". Information on ttysnoop seems to be pretty difficult to find online (I don't think it's been updated in quite a few years; for example, the first result on Google for "ttysnoop" has only dead links to tarballs, RPMs, and .deb's), and this request for a port to OS X received the response "No luck, it requires some linux specific utmp functions which I can't create."

I'm open to any suggestions on how to redirect the output (it doesn't have to use ttysnoop).

Thanks!

解决方案

The stdin and stdout fds are being inherited by the C shared library.

from fortran_code import fortran_function
import os

print "will run fortran function!"

# open 2 fds
null_fds = [os.open(os.devnull, os.O_RDWR) for x in xrange(2)]
# save the current file descriptors to a tuple
save = os.dup(1), os.dup(2)
# put /dev/null fds on 1 and 2
os.dup2(null_fds[0], 1)
os.dup2(null_fds[1], 2)

# *** run the function ***
fortran_function()

# restore file descriptors so I can print the results
os.dup2(save[0], 1)
os.dup2(save[1], 2)
# close the temporary fds
os.close(null_fds[0])
os.close(null_fds[1])

print "done!"

这篇关于用Python重定向FORTRAN(通过F2PY调用)输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 10:28