Module | Open3 |
In: |
lib/open3.rb
|
Open3 grants you access to stdin, stdout, and stderr when running another program. Example:
require "open3" include Open3 stdin, stdout, stderr = popen3('nroff -man')
Open3.popen3 can also take a block which will receive stdin, stdout and stderr as parameters. This ensures stdin, stdout and stderr are closed once the block exits. Example:
require "open3" Open3.popen3('nroff -man') { |stdin, stdout, stderr| ... }
Open stdin, stdout, and stderr streams and start external executable. Non-block form:
require 'open3' stdin, stdout, stderr = Open3.popen3(cmd)
Block form:
require 'open3' Open3.popen3(cmd) { |stdin, stdout, stderr| ... }
The parameter cmd is passed directly to Kernel#exec.
_popen3_ is like system in that you can pass extra parameters, and the strings won‘t be mangled by shell expansion.
stdin, stdout, stderr = Open3.popen3('identify', '/weird path/with spaces/and "strange" characters.jpg') result = stdout.read
# File lib/open3.rb, line 52 52: def popen3(*cmd) 53: pw = IO::pipe # pipe[0] for read, pipe[1] for write 54: pr = IO::pipe 55: pe = IO::pipe 56: 57: pid = fork{ 58: # child 59: fork{ 60: # grandchild 61: pw[1].close 62: STDIN.reopen(pw[0]) 63: pw[0].close 64: 65: pr[0].close 66: STDOUT.reopen(pr[1]) 67: pr[1].close 68: 69: pe[0].close 70: STDERR.reopen(pe[1]) 71: pe[1].close 72: 73: exec(*cmd) 74: } 75: exit!(0) 76: } 77: 78: pw[0].close 79: pr[1].close 80: pe[1].close 81: Process.waitpid(pid) 82: pi = [pw[1], pr[0], pe[0]] 83: pw[1].sync = true 84: if defined? yield 85: begin 86: return yield(*pi) 87: ensure 88: pi.each{|p| p.close unless p.closed?} 89: end 90: end 91: pi 92: end