如何立即打印标准输出? [英] How to print stdout immediately?

查看:238
本文介绍了如何立即打印标准输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何立即输出stdout?完成所有输入后,stdout将要打印.

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:

file_to_test.rb:

puts "please, enter s"
puts "please, enter q"

s = gets.chomp!
q = gets.chomp!

puts s
puts q

运行main.rb之后的结果是:

The result after running main.rb is:

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

如何立即输出stdout?

推荐答案

Ruby将缓冲输出,直到输出缓冲区已满.要更改行为以使其自动写入,请使用 sync sync= :

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

摘自sync=的文档:

将同步模式"设置为true或false.当同步模式为true时,所有输出将立即刷新到基础操作系统,并且不会在内部进行缓冲.

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.

重要的是要理解,启用缓冲区的自动刷新实际上会减慢代码的整体执行速度,尤其是当您正在写入要分块接收其数据的文件或设备时.使用sync或仔细冲洗.

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.

这篇关于如何立即打印标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆