Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Ruby脚本中重定向标准输出时出现问题_Ruby_Stdout_Stderr_Buffering_Output Redirect - Fatal编程技术网

在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

我有以下测试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 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缓冲,这很有趣,也很好。为了更好地理解这一切,我贴了一个帖子。