Add the following code to your project's shard.yml under:
to use in production
- OR -
development_dependencies to use in development
A small Crystal library for capturing standard I/O streams.
Add this to your application's
dependencies: stdio: github: mosop/stdio
require "stdio" out, err, in = Stdio.capture do |io| STDOUT.puts ":)" STDERR.puts ":(" io.in.puts ":P" [io.out.gets, io.err.gets, STDIN.gets] end puts out # prints ":)" puts err # prints ":(" puts in # prints ":P"
err methods return decapturing I/Os. The type of the I/O means that the I/O is not capturing the standard I/O any more. In other words, you can not capture the decaptured standard I/O again in the same yielded block after calling
Stdio.capture do |io| STDOUT.puts ":)" # captured io.out.gets # decaptured and taken ":)\n" STDOUT.puts ":X" # ":X" is printed, not captured end
Why is decapturing needed? Because a process easily hangs up when you send any waiting methods to I/Os that are still capturing the standard I/Os.
To read I/Os keeping capturing and control waiting by yourself, use the
Stdio.capture do |io| STDOUT.puts ":)" io.out!.gets # => ":)\n" STDOUT.puts ":X" io.out!.gets # => ":X\n" io.out!.gets # waits end