python - 悄悄导入rpy

标签 python r rpy2

我的问题类似于 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
... ...

我想实现来自 herequiet_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/

相关文章:

python - 系列的真值是不明确的。使用 panda python 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

Python 导入迭代,sys.path

python - 箭袋 matplotlib : arrow with the same sizes

json - 使用 tidyjson 从 JSON 中提取数组

R/MATLAB : restricting which libraries can be loaded

python - rpy2:检查包是否安装

python - 并行化使用 rpy2 的 python 代码的最有效方法是什么?

使用 rmagic 扩展的 Ipython 笔记本崩溃

python - 元组分组和堆栈

r - 提取R中每个单词的第一个字母