In R, we can open a pipe connection using pipe()
and write to it. I observed the following situation that I do not quite understand. Let's use a python
pipe for example:
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)
What I was expecting was the output from print()
would be immediately shown in the R console, but the fact is the output comes only after I close the pipe connection:
> 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
So my question is, how can I get the output before I close the connection? Note that it does not seem to be possible to capture the output using capture.output()
, either:
> 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)
The background of this question is the knitr
engines. For the interpreted languages like Python, I wish I can open a persistent "terminal" so that I can keep on writing code into it and get output from it. I'm not sure if pipe()
is the correct way to go, though.