简体   繁体   English

Ruby:即使没有换行符也可以获取外部命令的输出

[英]Ruby : get output of external command even when there is no line break

I try to run an external command in Ruby, and parse its output . 我尝试在Ruby中运行外部命令,然后解析其输出。

 IO.popen(command, :err=>[:child, :out]) {|ls_io|
  ls_io.each do |line| 
   print line   
 end
 }

This way of doing it works wonders… except when I parse the progress-output of a c-program that shows it progress to stdout with \\r. 这种处理方式令人惊奇……除了当我解析一个显示用\\ r向stdout进度的c程序的progress-output时。

As long as the c-program has not outputted a \\n (that is as long as it has not finished some long-operation), Ruby waits and sees nothing. 只要c程序没有输出\\ n(即只要它没有完成一些长时间的操作),Ruby就会等待并且什么也看不到。 Then when a \\n is outputted, Ruby sees it all 然后,当输出\\ n时,Ruby会看到所有内容

1%\r2%\r3%\r…100%
task finished

I tried all of the many ways to call external commands (eg Calling shell commands from Ruby ) ; 我尝试了所有多种方法来调用外部命令(例如, 从Ruby调用shell命令 ); but none seem to capture the progress. 但似乎没有人捕捉到进展。 I also tried every opeartor such as STDOUT.sync = true , and the c-program does call fflush(stdout) 我还尝试了每个操作器,例如STDOUT.sync = true ,并且C程序确实调用了fflush(stdout)

I finally found a workaroud. 我终于找到了一个工作狂。 I do : 我做 :

IO.popen(commande, :err=>[:child, :out]) {|ls_io|
while true
  byte=ls_io.read(1)
  if byte.nil?
    break
  end
   print byte
end
}

It's stupid… but it works. 这很愚蠢……但是有效。

Any more elegant way, and much more efficient way to do this ? 还有其他更优雅的方法,以及更有效的方法吗? Performance is terrible, as if the "refresh rate" was slow. 性能很糟糕,好像“刷新率”很慢。

Set the input record separator to "\\r" right before your block (provided you know it in advance): 在块之前将输入记录分隔符设置为“ \\ r”(前提是您事先知道):

$/ = "\r"

Reference of global preset variables: http://www.zenspider.com/Languages/Ruby/QuickRef.html#pre-defined-variables 全局预设变量的参考: http : //www.zenspider.com/Languages/Ruby/QuickRef.html#pre-defined-variables

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM