我有一个 R 函数,我使用 rpy2 从 Python 脚本中调用它。 R 函数打印到 stdout; rpy2 中是否有一个参数可以在调用 R 脚本时使 stdout 静音?
最佳答案
rpy2 允许您将 R 自身与终端的交互重新定义为 python 函数。
文档中的以下示例显示了如何附加输出
到 stdout
到 Python 列表(在宏伟的计划中用途有限,但它提供了该功能的简单示例):
buf = []
def f(x):
# function that append its argument to the list 'buf'
buf.append(x)
consolewrite_print_backup = (rpy2.rinterface_lib.callbacks
.consolewrite_print)
# output from the R console will now be appended to the list 'buf'
rpy2.rinterface_lib.callbacks.consolewrite_print = 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
rpy2.rinterface_lib.callbacks.consolewrite_print = consolewrite_print_backup
文档位于:https://rpy2.github.io/doc/v3.3.x/html/callbacks.html#write-console
关于python - 如何在 rpy2 中静默输出到 stdout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38793688/