在Ruby脚本中重定向标准输出时出现问题
我有以下测试Ruby脚本:在Ruby脚本中重定向标准输出时出现问题,ruby,stdout,stderr,buffering,output-redirect,Ruby,Stdout,Stderr,Buffering,Output Redirect,我有以下测试Ruby脚本: require 'tempfile' tempfile = Tempfile.new 'test' $stderr.reopen tempfile $stdout.reopen tempfile puts 'test stdout' warn 'test stderr' `mail -s 'test' my@email.com < #{tempfile.path}` tempfile.close tempfile.unlink $stderr.reopen
require 'tempfile'
tempfile = Tempfile.new 'test'
$stderr.reopen tempfile
$stdout.reopen tempfile
puts 'test stdout'
warn 'test stderr'
`mail -s 'test' my@email.com < #{tempfile.path}`
tempfile.close
tempfile.unlink
$stderr.reopen STDERR
$stdout.reopen STDOUT
为什么stderr重定向正确而不是stdout
编辑:为了回应一条评论,我在
放置
行后添加了一个$stdout.flush
,并且打印正确。因此,我要重申我的问题:发生了什么,为什么刷新会修复它?标准输出通常是缓冲的,以避免每次写入都进行系统调用。所以,当你这么说的时候:
puts 'test stdout'
`mail -s 'test' my@email.com < #{tempfile.path}`
实际上,您只是将该字符串填充到缓冲区中。然后你说:
puts 'test stdout'
`mail -s 'test' my@email.com < #{tempfile.path}`
产生:
no newline
标准错误通常是无缓冲的,因此错误消息(应该很少)会立即可见。当您切换警告和puts的顺序时会发生什么?当我切换
warn
和puts
的顺序时不会发生什么@穆:我把邮件
改成了猫
,和你写的一模一样,但我还是没有打印标准件。我正在CentOS Linux上使用Ruby Enterprise Edition 2011.01。关于stderr缓冲,这很有趣,也很好。为了更好地理解这一切,我贴了一个帖子。