我有一个R函数,我使用rpy2从我的Python脚本调用。 R函数打印到stdout; rpy2中是否有一个参数在调用R脚本时使stdout静音?
答案 0 :(得分:1)
rpy2允许您将自己与终端的交互重新定义为python函数。
文档中的以下示例显示了如何附加输出
到stdout
到Python列表(在宏观方案中有限的用处,但它是一个简单的功能示例):
buf = []
def f(x):
# function that append its argument to the list 'buf'
buf.append(x)
# output from the R console will now be appended to the list 'buf'
rinterface.set_writeconsole(f)
date = rinterface.baseenv['date']
rprint = rinterface.baseenv['print']
rprint(date())
# the output is in our list (as defined in the function f above)
print(buf)
# restore default function
rinterface.set_writeconsole(rinterface.consolePrint)
文档在这里:http://rpy2.readthedocs.io/en/version_2.8.x/callbacks.html#console-i-o
答案 1 :(得分:0)
@lgautier的答案在rpy2
的最新版本中无效,该版本在撰写本文时为3.3.5。
此方法可以附加到一个类上,并且在被调用一次之后,会将R的所有输出捕获到两个属性中。
def capture_r_output(self):
"""
Will cause all the output that normally goes to the R console,
to end up instead in a python list.
"""
# Import module #
import rpy2.rinterface_lib.callbacks
# Record output #
self.stdout = []
self.stderr = []
# Dummy functions #
def add_to_stdout(line): self.stdout.append(line)
def add_to_stderr(line): self.stderr.append(line)
# Keep the old functions #
self.stdout_orig = rpy2.rinterface_lib.callbacks.consolewrite_print
self.stderr_orig = rpy2.rinterface_lib.callbacks.consolewrite_warnerror
# Set the call backs #
rpy2.rinterface_lib.callbacks.consolewrite_print = add_to_stdout
rpy2.rinterface_lib.callbacks.consolewrite_warnerror = add_to_stderr