5

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.

Community
  • 1
  • 1
Zhang18
  • 4,800
  • 10
  • 50
  • 67

1 Answers1

8

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.

reclosedev
  • 9,352
  • 34
  • 51
  • 1
    Could DummyFile() also be replaced with: `open(os.devnull, "w")` ? I like this contextmanager approach BTW – jdi Dec 19 '11 at 17:33
  • 1
    You can find similar solutions [here](http://stackoverflow.com/q/8522689/183066). There are some changes that would make the code even better in my opinion: using `os.devnull` and using `sys.__stderr__` and `sys.__stdout__` to get the original `sys.stderr` and `sys.stdout` (no need to keep the values). – jcollado Dec 19 '11 at 17:34
  • @jdi, jcollado, i like your advices. Added improvements to code. – reclosedev Dec 19 '11 at 17:58