Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print stdout immediately?

How can I immediately output stdout? stdout is going to print after all 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 is:

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

How can I immediately output stdout?

like image 686
xitryuga Avatar asked Oct 07 '16 15:10

xitryuga


People also ask

How do I print to stdout?

In C, to print to STDOUT, you may do this: printf("%sn", your_str); For example, $ cat t.c #include <stdio.

What is stdout flush?

stdout. flush() forces it to “flush” the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.

How do you flush stdout in Rust?

Macro std::print Note that stdout is frequently line-buffered by default so it may be necessary to use io::stdout(). flush() to ensure the output is emitted immediately. Use print! only for the primary output of your program.

What is stdout Ruby?

The $stdout is a global variable which holds the standard output stream. printing2.rb. #!/usr/bin/ruby $stdout.print "Ruby language\n" $stdout.puts "Python language" We print two lines using the $stdout variable. Ruby has another three methods for printing output.


1 Answers

Ruby is buffering output until the output buffer is full. To change the behavior so it automatically writes use 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 “sync mode” to true or false. When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered internally.

It's important to understand that enabling automatic flushing of the buffer can actually slow the overall execution speed of your code, especially if you're writing to a file or device that wants to receive its data in chunks. Use sync or flushing carefully.

like image 154
the Tin Man Avatar answered Sep 19 '22 01:09

the Tin Man