安静地导入 rpy

发布于 2024-12-22 05:21:32 字数 712 浏览 2 评论 0原文

我的问题类似于这个 但在通过 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
... ...

我想实现 此处 但不知道它如何适合导入上下文所有模块。

我知道这是可能的,因为在另一个盒子上运行的同一程序不会输出任何消息。

更新:这不必必须在Python中解决。如果我可以以某种方式调整 R 端的变量以允许所有调用保持安静,那么这也是可行的。我只是不知道该怎么做。

My question is analogous to this one but in the context of importing R to Python via RPy. Specifically, when I run

from rpy import *

at the beginning of my python script, there is a chunk of message dumped to the screen (or output device), starting with

Parsing output:  R version 2.13.2 (2011-09-30)
Copyright (C) 2011 The R Foundation for Statistical Computing
... ...

I wanted to implement the quiet_require from here but don't see how it fits in the context of importing all modules.

I know this is possible because the same program running on another box doesn't output any message.

UPDATE: this does not have to be solved within Python. If I can somehow tweak a variable on the R side to allow all invocations to be quiet, that works too. I just don't know how to do that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半寸时光 2024-12-29 05:21:32

这是简单但不漂亮的黑客:

# 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的建议更改了代码。

Here is simple but not beatiful hack:

# 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 

edit: changed code as advised @jdi and @jcollado.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文