python - 如何在 rpy2 中静默输出到 stdout?

标签 python r rpy2

我有一个 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/

相关文章:

python - 使用 Visual Studio Code 将请求导入 Python

python - 为什么 django 忽略线路中的 HTTP_X_FORWARDED_PROTO 而不是在测试中?

r - rm.outlier函数在data.frame中出现错误

macos - 用貌似不存在的SDK编译 :/Developer/SDKs/MacOSX10. 6.sdk

python - LightGBM on Numerical+Categorical+Text Features >> TypeError : Unknown type of parameter:boosting_type, got:dict

python - 线段树的最小值和最大值

R - 具有固定精度的 write.csv

r - 在 R 中绘制 ellipse3d?

python - 如何创建一个空的 R 向量来添加新项目

python - Jupyter + rpy2 输出到命令提示符而不是笔记本单元格