我有以下测试 Ruby 脚本:
require 'tempfile'
tempfile = Tempfile.new 'test'
$stderr.reopen tempfile
$stdout.reopen tempfile
puts 'test stdout'
warn 'test stderr'
`mail -s 'test' [email protected] /cdn-cgi/l/email-protection < #{tempfile.path}`
tempfile.close
tempfile.unlink
$stderr.reopen STDERR
$stdout.reopen STDOUT
我收到的电子邮件内容如下:
test stderr
为什么 stderr 可以正确重定向,但 stdout 却不能正确重定向?
Edit:为了回应评论,我添加了一个$stdout.flush
之后puts
行并正确打印。所以我会重申我的问题:发生了什么以及为什么冲洗可以修复它?
标准输出通常会被缓冲,以避免每次写入时都进行系统调用。所以,当你这样说时:
puts 'test stdout'
实际上,您只是将该字符串填充到缓冲区中。然后你这样说:
`mail -s 'test' [email protected] /cdn-cgi/l/email-protection < #{tempfile.path}`
和你的'test stdout'
字符串仍在缓冲区中,因此它不在tempfile
when mail
将文件的内容发送给您。法拉盛$stdout
强制将缓冲区中的所有内容写入磁盘;来自精美手册 https://ruby-doc.org/core/IO.html#method-i-flush:
将 ios 内的任何缓冲数据刷新到底层操作系统(请注意,这只是 Ruby 内部缓冲;操作系统也可以缓冲数据)。
$stdout.print "no newline"
$stdout.flush
产生:
no newline
标准错误通常是未缓冲的,因此错误消息(应该很少见)立即可见。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)