Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top