在 Ruby 脚本中重定向 stdout 时出现问题
我有以下测试 Ruby 脚本:
require 'tempfile'
tempfile = Tempfile.new 'test'
$stderr.reopen tempfile
$stdout.reopen tempfile
puts 'test stdout'
warn 'test stderr'
`mail -s 'test' [email protected] < #{tempfile.path}`
tempfile.close
tempfile.unlink
$stderr.reopen STDERR
$stdout.reopen STDOUT
我收到的电子邮件内容如下:
test stderr
为什么 stderr 正确重定向,但 stdout 不正确?
编辑:为了响应评论,我在 puts
行之后添加了一个 $stdout.flush
,并且它打印正确。所以我会重申我的问题:发生了什么以及为什么冲洗可以修复它?
I have the following test Ruby script:
require 'tempfile'
tempfile = Tempfile.new 'test'
$stderr.reopen tempfile
$stdout.reopen tempfile
puts 'test stdout'
warn 'test stderr'
`mail -s 'test' [email protected] < #{tempfile.path}`
tempfile.close
tempfile.unlink
$stderr.reopen STDERR
$stdout.reopen STDOUT
The email that I get has the contents:
test stderr
Why is stderr redirecting properly but not stdout?
Edit: In response to a comment I added a $stdout.flush
after the puts
line and it printed correctly. So I'll restate my question: what was happening and why does the flush fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
标准输出通常会被缓冲,以避免每次写入时都进行系统调用。所以,当你这样说时:
你实际上只是将该字符串填充到缓冲区中。然后你这样说:
并且你的
'test stdout'
字符串仍在缓冲区中,因此当mail
发送文件的时它不在tempfile
中内容给你。刷新$stdout
强制将缓冲区中的所有内容写入磁盘;来自精细手册:标准错误通常是未缓冲的,因此错误消息(应该很少见)立即可见。
The standard output is generally buffered to avoid a system call for every write. So, when you say this:
You're actually just stuffing that string into the buffer. Then you say this:
and your
'test stdout'
string is still in the buffer so it isn't intempfile
whenmail
sends the file's content to you. Flushing$stdout
forces everything in the buffer to be written to disk; from the fine manual:The standard error is often unbuffered so that error messages (which are supposed to be rare) are visible immediately.