【问题标题】:How do I silence output to stdout in rpy2?如何在 rpy2 中将输出静音到标准输出?
【发布时间】:2016-08-05 16:14:38
【问题描述】:

我有一个 R 函数,我使用 rpy2 从我的 Python 脚本中调用它。 R 函数打印到标准输出; rpy2 中是否有一个参数可以在调用 R 脚本时使标准输出静音?

【问题讨论】:

  • 您可以使用StringIO 停止stdout 的写入。在 Python 2 中位于 StringIo 模块中,在 Python 3 中位于 io 模块中。
  • 从R端可以使用invisible(expression)隐藏打印方式

标签: python r rpy2


【解决方案1】:

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

【讨论】:

  • 这似乎不适用于最新版本的rpy2,截至撰写时为 3.3.5。
  • @xApple - 答案是针对旧版本的 rpy2。 rpy2-3.3.5 的文档有一个适用于匹配版本的版本。答案已编辑为指向文档的最新版本。
【解决方案2】:

@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

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 2013-05-01
    • 2012-05-03
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    相关资源
    最近更新 更多