R中的读写管道()通信

mjb*_*mar 11 ipc r pipe

大多数语言都支持双向进程通信.例如,在Python中,我可以(懒散地)做:

>>> from subprocess import *
>>> p = Popen('nslookup', stdin=PIPE, stdout=PIPE)
>>> p_stdin, p_stdout = p.communicate("www.google.com")
>>> print p_stdin
Server:     ...
Run Code Online (Sandbox Code Playgroud)

在R中,无论是否用"r +"或"w +"打开我的管道,我似乎只能走一条路.此外,即使我通过R -f ...或运行脚本R < ...,在实际的控制台stdin/stdout中也会出现奇怪的行为.

我的问题可归结为以下内容 - 是否有可能(无需编写C方法!)在R中的上述Python示例中重现双向进程通信?

Sha*_*pie 11

这样做的类UNIX系统的一种方法是打开一个管道被重定向的过程stdout,并stderr到FIFO:

# Setup
system('mkfifo output.fifo')
p_out <- fifo('output.fifo', 'r')
p_in <- pipe('pdflatex &> output.fifo', 'w')

# See what TeX said on startup
readLines(p_out)
[1] "This is pdfTeX, Version 3.1415926-1.40.11 (TeX Live 2010)"

readLines(p_out)
character(0) # TeX has nothing more to say

# Tell TeX to do something
writeLines('\\documentclass{article}', p_in)
flush(p_in)

# See what it said in response
readLines(p_out)
[1] "**entering extended mode"                                                       
[2] "LaTeX2e <2009/09/24>"                                                           
[3] "Babel <v3.8l> and hyphenation patterns for english, dumylang, nohyphenation, ba"
[4] "sque, danish, dutch, finnish, french, german, ngerman, swissgerman, hungarian, "
[5] "italian, bokmal, nynorsk, polish, portuguese, spanish, swedish, loaded."        
[6] ""
Run Code Online (Sandbox Code Playgroud)

不幸的是,fifoWindows不支持.


Dir*_*tel 5

很久以前我也在Octave 中使用了双向管道所以,是的,这会很好。但仔细阅读help(pipe)并不表明这是支持。你会读写,但似乎不是两者兼而有之。

但也许你可以作弊。打开一个管道以写入一个应用程序,您可以使用 stdout 重定向到一个文件来调用该应用程序......然后继续读取该文件。不过,由于未刷新的缓冲区,可能会一团糟。