我的问题类似于 this one但在通过 RPy 将 R 导入 Python 的上下文中。具体来说,当我运行时
from rpy import *
在我的 python 脚本的开头,有一大块消息被转储到屏幕(或输出设备),以
开头Parsing output: R version 2.13.2 (2011-09-30)
Copyright (C) 2011 The R Foundation for Statistical Computing
... ...
我想实现来自 here 的 quiet_require
但看不到它如何适合导入所有 模块的上下文。
我知道这是可能的,因为在另一个盒子上运行的同一个程序不会输出任何消息。
更新:这不必须在 Python 中解决。如果我能以某种方式调整 R 端的变量以允许所有调用安静,那也行得通。我只是不知道该怎么做。
最佳答案
这是一个简单但不漂亮的技巧:
# define somewhere following:
import sys
import os
from contextlib import contextmanager
@contextmanager
def quiet():
sys.stdout = sys.stderr = open(os.devnull, "w")
try:
yield
finally:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
# use it
with quiet():
# all is quiet in this scope
import this # just for testing
from rpy import * # or whatever you want
# and this will print something
import something_that_prints
编辑按照@jdi 和@jcollado 的建议修改了代码。
关于python - 悄悄导入rpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8564741/