Yih*_*Xie 5 r stdout pipe knitr
在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)
Run Code Online (Sandbox Code Playgroud)
我期待的是输出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
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,在关闭连接之前如何获得输出?请注意,似乎无法使用以下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)
Run Code Online (Sandbox Code Playgroud)
这个问题的背景是knitr引擎.对于像Python这样的解释语言,我希望我可以打开一个持久的"终端",这样我就可以继续编写代码并从中获取输出.不过,我不确定这是否pipe()是正确的方法.
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)
Run Code Online (Sandbox Code Playgroud)
您的实际问题更复杂:您需要同时读取和写入同一连接.我不知道如何以便携方式执行此操作,但您可以在支持它们的平台上使用管道和命名管道("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"
Run Code Online (Sandbox Code Playgroud)