【问题标题】:how to get output from a pipe connection before closing it in R?如何在 R 中关闭管道连接之前从管道连接中获取输出?
【发布时间】:2013-07-19 22:30:02
【问题描述】:

在 R 中,我们可以使用pipe() 打开一个管道连接并写入它。我观察到以下我不太明白的情况。我们以python 管道为例:

z = pipe('python', open='w+')

cat('x=1\n', file=z)
cat('print(x)\n', file=z)
cat('print(x+2)\n', file=z)
cat('print(x+2\n', file=z)
cat(')\n', file=z)

close(z)

我所期望的是print() 的输出会立即显示在 R 控制台中,但事实是输出仅在我关闭管道连接后出现:

> z = pipe('python', open='w+')
> 
> cat('x=1\n', file=z)
> cat('print(x)\n', file=z)
> cat('print(x+2)\n', file=z)
> cat('print(x+2\n', file=z)
> cat(')\n', file=z)
> 
> close(z)
1
3
3

所以我的问题是,如何在关闭连接之前获得输出?请注意,使用capture.output() 似乎也无法捕获输出:

> z = pipe('python', open='w+')
> 
> cat('x=1\n', file=z)
> cat('print(x)\n', file=z)
> cat('print(x+2)\n', file=z)
> cat('print(x+2\n', file=z)
> cat(')\n', file=z)
> 
> x = capture.output(close(z))
1
3
3
> x
character(0)

这个问题的背景是knitr engines。对于像 Python 这样的解释型语言,我希望我可以打开一个持久的“终端”,这样我就可以继续向其中写入代码并从中获取输出。不过,我不确定pipe() 是否正确。

【问题讨论】:

    标签: r pipe stdout knitr


    【解决方案1】:

    Python 注意到输入不是交互式的,并等待连接关闭以解析和执行代码。您可以使用-i 选项强制它保持交互模式。 (但输出有点混乱)。

    z = pipe('python -i', open='w')
    cat('x=1\n', file=z)
    cat('print(x)\n', file=z)
    cat('print(x+2)\n', file=z)
    cat('print(x+2\n', file=z)
    cat(')\n', file=z)
    Sys.sleep(2)
    # Python 2.7.4 (default, Apr 19 2013, 18:28:01) 
    # [GCC 4.7.3] on linux2
    # Type "help", "copyright", "credits" or "license" for more information.
    # >>> >>> 1
    # >>> 3
    # >>> ... 3
    # >>> 
    close(z)
    

    您的实际问题更复杂:您需要同时读取和写入同一个连接。 我不知道如何以可移植的方式做到这一点,但您可以在支持它们的平台上使用管道和命名管道(“fifo”)。

    stopifnot( capabilities("fifo") )
    system('mkfifo /tmp/Rpython.fifo')
    output <- fifo('/tmp/Rpython.fifo', 'r')
    input  <- pipe('python -i > /tmp/Rpython.fifo', 'w')
    python_code <- "
    x=1
    print(x)
    print(x+2)
    print(x+2
    )
    "
    cat( python_code, file = input )
    flush( input )
    Sys.sleep(2) # Wait for the results
    result <- readLines(output)
    result
    # [1] "1" "3" "3"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      • 1970-01-01
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多