我可以在Ruby中显示系统调用的日志吗?



我需要调用这样的命令(在sinatra或rails应用程序中):

`command sub`

命令执行时会输出一些日志。我想看到日志在这个过程中连续显示。

但是我只能在它完成后得到日志字符串:

result = `command sub`

那么,有办法实现这个吗?

在windows上我使用IO.popen的体验最好

这是一个示例

require 'logger'
$log = Logger.new( "#{__FILE__}.log", 'monthly' )
#here comes the full command line, here it is a java program
command = %Q{java -jar getscreen.jar #{$userid} #{$password}}
$log.debug command
STDOUT.sync = true
begin
  # Note the somewhat strange 2> syntax. This denotes the file descriptor to pipe to a file. By convention, 0 is stdin, 1 is stdout, 2 is stderr.
  IO.popen(command+" 2>&1") do |pipe|
    pipe.sync = true
    while str = pipe.gets #for every line the external program returns
      #do somerthing with the capturted line
    end
  end
rescue => e
  $log.error "#{__LINE__}:#{e}"
  $log.error e.backtrace
end

有六种方法可以做到这一点,但您使用的方法不正确,因为它等待进程返回。

从这里选一个:

http://tech.natemurray.com/2007/03/ruby-shell-commands.html

如果我是你,我会用IO#popen3

最新更新