【问题标题】:Can I display the log of system call in Ruby?我可以在 Ruby 中显示系统调用的日志吗?
【发布时间】:2014-07-21 15:59:00
【问题描述】:

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

`command sub`

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

但我只是可以在完成后获取日志字符串:

result = `command sub`

那么,有没有办法实现呢?

【问题讨论】:

    标签: ruby-on-rails ruby shell sinatra


    【解决方案1】:

    在 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
    

    【讨论】:

      【解决方案2】:

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

      从这里选择一个:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-10
        • 1970-01-01
        • 2013-03-18
        • 2011-07-08
        • 2021-06-09
        • 1970-01-01
        • 1970-01-01
        • 2012-11-05
        相关资源
        最近更新 更多