popen(p1, p2 = v2) public

Runs the specified command as a subprocess; the subprocess’s standard input and output will be connected to the returned IO object. If cmd is a String “-”, then a new instance of Ruby is started as the subprocess. If cmd is an Array of String, then it will be used as the subprocess’s argv bypassing a shell. The array can contains a hash at first for environments and a hash at last for options similar to spawn. The default mode for the new file object is “r”, but mode may be set to any of the modes listed in the description for class IO. The last argument opt qualifies mode.

# set IO encoding
nkf_io = IO.popen("nkf -e filename", :external_encoding=>"EUC-JP")
euc_jp_string = nkf_io.read

# discard standard error using spawn option.
# See the document of Kernel.spawn.
ls_io = IO.popen(["ls", "/", :err=>"/dev/null"])
ls_result_with_error = ls_io.read

Raises exceptions which IO.pipe and Kernel.spawn raise.

If a block is given, Ruby will run the command as a child connected to Ruby with a pipe. Ruby’s end of the pipe will be passed as a parameter to the block. At the end of block, Ruby close the pipe and sets $?. In this case IO.popen returns the value of the block.

If a block is given with a cmd of “-”, the block will be run in two separate processes: once in the parent, and once in a child. The parent process will be passed the pipe object as a parameter to the block, the child version of the block will be passed nil, and the child’s standard in and standard out will be connected to the parent through the pipe. Not available on all platforms.

f = IO.popen("uname")
p f.readlines
puts "Parent is #{Process.pid}"
IO.popen("date") { |f| puts f.gets }
IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f}"}
p $?
IO.popen(%w"sed -e s|^|<foo>| -e s&$&;zot;&", "r+") {|f|
  f.puts "bar"; f.close_write; puts f.gets


Parent is 26166
Wed Apr  9 08:53:52 CDT 2003
26169 is here, f is
26166 is here, f is #<IO:0x401b3d44>
#<Process::Status: pid=26166,exited(0)>
Show source
Register or log in to add new notes.