在 Python 中重定向 FORTRAN(通过 F2PY 调用)输出 [英] Redirecting FORTRAN (called via F2PY) output in Python

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

问题描述

我想弄清楚如何重定向某些 FORTRAN 代码的输出,我已经使用 F2PY 为其生成了 Python 接口.我试过了:

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

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

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).

我确实找到了 2002 年的邮件列表帖子 说可以从 pts 设备读取消息,例如 ttysnoop 可以做到这一点".关于 ttysnoop 的信息似乎很难在网上找到(我认为它已经好几年没有更新了;例如,Google 上关于ttysnoop"的第一个结果只有指向 tarball、RPM 和 .deb 的无效链接)和 这个对 OS X 端口的请求 收到了响应不走运,它需要一些我无法创建的特定于 linux 的 utmp 函数."

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."

我愿意接受有关如何重定向输出的任何建议(不必使用 ttysnoop).

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

谢谢!

推荐答案

stdin 和 stdout fds 由 C 共享库继承.

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 调用)输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆