【问题标题】:Capture and process output from external commands from R捕获和处理来自 R 的外部命令的输出
【发布时间】:2014-11-02 23:22:59
【问题描述】:

以这个简单的python脚本为例:

#!/usr/bin/env python3

# /tmp/xxx.py

import time

for i in range(1000):
    print(i)
    time.sleep(1)

它连续输出数字。我可以像这样从 R 中调用它:

system2("/tmp/xxx.py", stdin=?)

其中 stdin 可以设置为 NULL、""、TRUE 或文件名。但我正在寻找的是一种实时处理这些数字的方法。例如,每当从这个 python 脚本打印一个数字时,我想将该数字乘以 Pi,然后将其打印到控制台。有没有办法在 R 中做到这一点?

【问题讨论】:

  • 对我的回答的任何反馈将不胜感激。你知道 SO 是如何工作的……我花了将近一个小时。

标签: r io stdout


【解决方案1】:

不是专家,但我有一些工作。

首先,我使用以下/tmp/xxx.R 可执行Rscript 而不是您的python 脚本,因为我发现python 正在缓冲其输出(一次不打印一行),这使得测试变得困难:

#!/usr/bin/env Rscript

for (i in 1:5) {
   cat(i, "\n")
   Sys.sleep(1)
}

然后是R代码:

system('mkfifo /tmp/xxx.fifo')
f <- fifo("/tmp/xxx.fifo", 'r')
p <- pipe('/tmp/xxx.R > /tmp/xxx.fifo; echo OVER > /tmp/xxx.fifo', 'w')

while(TRUE) {
   line <- readLines(f, n = 1)
   if (length(line) > 0) {
      if (line == "OVER") break
      cat(pi * as.numeric(line), "\n")
   }
   Sys.sleep(0.1)
}
close(f)
close(p)

其中一些灵感来自此:https://stackoverflow.com/a/5561188/1201032

希望它能回答你的问题。

【讨论】:

  • 抱歉回复晚了,我胡思乱想想出了这个问题,然后就忘记了,你知道,这些事情发生了。这在 Linux 和 osx 上运行良好。可能无法在 Windows 上运行?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 2017-02-26
  • 2013-01-16
相关资源
最近更新 更多