Recipe 6.16. Redirecting Standard Input or OutputProblemYou don't want the standard input, output, or error of your process to go to the SolutionYou can This short Ruby program demonstrates how to redirect the Kernel methods that print to standard output. To avoid confusion, I'm presenting it as a standalone Ruby program rather than an interactive irb session.[4]
Run this program and you'll see the following:
DiscussionIf you have any Unix experience, you know that when you run a Ruby script from the command line, you can make the shell redirect its standard You can use this as a quick and dirty way to write errors to a file, write output to a StringIO object (as seen above), or even read input from a socket. Within a script, you can programatically decide where to send your output, or receive standard input from multiple sources. These things are generally not possible from the command line without a lot of fancy shell scripting. The redirection technique is especially useful when you've written or inherited a script that prints text to standard output, and you need to make it capable of printing to any file-like object. Rather than changing almost every line of your code, you can just set $stdout at the start of your program, and let it run as is. This isn't a perfect solution, but it's often good enough. The original input and output streams for a process are always available as the constants STDIN, STDOUT, and STDERR. If you want to temporarily swap one IO stream for another, change back to the "standard" standard output by setting $stdin = STDIN. Keep in mind that since the $std objects are global variables, even a temporary change affects all threads in your script. See AlsoRecipe 6.15, "Pretending a String Is a File," has much more information on StringIO |
Tuesday, December 15, 2009
Recipe 6.16. Redirecting Standard Input or Output
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment