4

In a Python shell, and using rpy2 when I issue the following command

In [93]: x = robjects.r.bfast(data, h=0.1, season="none", max_iter=1)
[1]
 "No seasonal model will be fitted!"

I get this non-desirable output

[1]
 "No seasonal model will be fitted!"

Is there any way to suppress this output ? I would like to wrap this call to a function and then to an api call. Thus, redirecting output to stdout is non-desirable.

In other words, how to do in rpy2:

sink("/dev/null")

Is there a better way than

robjects.r('sink("/dev/null")')

?

Parfait
  • 104,375
  • 17
  • 94
  • 125
nskalis
  • 2,232
  • 8
  • 30
  • 49

1 Answers1

3

Apparently, the bfast method conditionally prints that message to console with no wrapper to not print which is not advisable code. Reach out to developers on a pull request.

Per this solution, consider R's capture.output which returns character string of output.

...
from rpy2.robjects.packages import importr

utils = importr('utils')    
bfast = importr('bfast')

# NOTICE R's PERIODS CHANGED TO UNDERSCORE TO FIT PYTHON'S OBJECT MODEL
x = utils.capture_output(bfast(data, h=0.1, season="none", max_iter=1))
Parfait
  • 104,375
  • 17
  • 94
  • 125
  • thanks @Parfait but why this is better than doing `robjects.r('sink("/dev/null")')` since i do not care about the `print` output ? – nskalis Jun 04 '17 at 16:15
  • R docs uses the analogy that `capture.output()` is to `sink()` as `with()` is to `attach()`. My guess is the former of these comparisons do not affect the global environment as the latter ones do but are restricted to the specific calling line, so lines before and after are not affected. – Parfait Jun 04 '17 at 16:20
  • I get an error: `module 'base' has no attribute 'capture_output'` – eotp Apr 19 '19 at 09:45
  • @eotp, [`capture.output`](https://stat.ethz.ch/R-manual/R-devel/library/utils/html/capture.output.html) is actually from the *utils* not *base* package (both part of R's standard library). See edit. – Parfait Apr 19 '19 at 14:30
  • @Parfait Thanks! – eotp Apr 22 '19 at 17:29