How to print stdout immediately?

How can I output stdout right away? stdout will print after input is complete.

 require 'open3' def run(cmd) Open3.popen3(cmd) do |stdin, stdout, stderr, thread| Thread.new do stdout.each {|l| puts l} end Thread.new do while thread.alive? stdin.puts $stdin.gets end end thread.join end end run ("ruby file_to_test.rb") 

file_to_test.rb:

 puts "please, enter s" puts "please, enter q" s = gets.chomp! q = gets.chomp! puts s puts q 

The result after running main.rb:

 somestring somestring2 please, enter s please, enter q somestring somestring2 

How can I output stdout right away?

+6
source share
2 answers

Ruby buffers until the output buffer is full. To change the behavior so that it automatically records the use of sync and sync= :

 old_sync = $stdout.sync $stdout.sync = true puts "immediately output lotsa stuff" puts "immediately output lotsa stuff" puts "immediately output lotsa stuff" puts "immediately output lotsa stuff" # reenable the default behavior $stdout.sync = old_sync 

From the documentation for sync= :

Sets the synchronization mode to true or false. When the synchronization mode is true, all output is immediately flushed from the underlying operating system and is not buffered internally.

It is important to understand that enabling automatic buffer cleaning can actually slow down the overall execution speed of your code, especially if you are writing a file or device that wants to receive its data in pieces. Use sync or rinse thoroughly.

+6
source

Reset output

What you are looking for is to flush the io stream using the flush method.

Try the following after each iteration or each of them puts:

 stdout.flush 

If you had several lines per line, I would suggest making a flush after the last one, so you don't do this too often. Example:

 stdout.puts "Hello" stdout.puts "Mate" stdout.flush 
+2
source

All Articles