Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

ipc - Read-write pipe() communication in R

Most languages support two-way process communication. For example, in Python, I can (sloppily) do:

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

In R, I can only seem to go one way, regardless of whether I open my pipe with "r+" or "w+". Furthermore, even if I run a script via R -f ... or R < ..., weird behavior ensues in the actual console stdin/stdout.

My question boils down to the following - is it possible (without writing a C method!) to reproduce the two-way process communication in the above Python example in R?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way to do it on UNIX-like systems would be to open a pipe to a process that is redirecting stdout and stderr to a 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] ""

Unfortunately, fifo isn't supported on Windows.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...