我试图弄清楚如何从一些FORTRAN代码中重定向输出,我已经使用F2PY为它们生成了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中重定向输出的事实上的方法,但是在这种情况下似乎不起作用(即,无论如何都会显示输出)。
我确实找到了2002年的邮件列表帖子,内容是“可以从pts设备读取消息,例如ttysnoop可以做到这一点”。关于ttysnoop的信息似乎很难在网上找到(我认为它已经有很多年没有更新了;例如,在Google上针对“ ttysnoop”的第一个结果只有指向tarball,RPM和.deb的无效链接)。 ),并且向OS X发出的端口请求收到响应“运气不好,它需要一些我无法创建的特定于Linux的utmp函数。”
我愿意就如何重定向输出(不必使用ttysnoop)提出任何建议。
谢谢!
C共享库继承了stdin和stdout fds。
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!"