为什么我的代码在irb中工作,而不是从脚本中工作?

时间:2015-04-16 17:06:59

标签: ruby redmine popen

我想对Redmine日志文件进行一些分析,包括以前的日志。所以我想catenate logfile.log.0和logfile.log,并一次循环输出一行。我写了以下代码:

module MyModule
   def analyze_log
     logfile = '/www/redmine/log/logfile.log'
     cat_cmd = "cat #{logfile}.0 #{logfile}"
     cat = IO.popen(cat_cmd)
     cat.readlines do |line|
        puts line
     end
  end
end

当我在irb中执行时,代码(没有模块和方法定义)完美地工作,但是当我将代码包装在方法(analyze_log)中时,它在同一台机器上不起作用(不打印行)一个模块(MyModule),并从脚本中调用它,如下所示:

#!/opt/ruby/bin/ruby
require './my_module'
include MyModule
analyze_log

是什么给出了?

顺便说一下,如果有更好的方法可以在同一个循环中顺序处理多个文件,我会很高兴听到它。但我主要担心的是它在irb中运行,但在以脚本运行时则不行。

我以与我运行irb的相同用户身份运行脚本。

3 个答案:

答案 0 :(得分:0)

尝试更改:

cat = IO.popen(cat_cmd)

为:

cat = exec(cat_cmd)

或者更改循环以遍历以下行:

cat = IO.popen(cat_cmd)
cat.readlines.each {|line| puts line }

答案 1 :(得分:0)

你试过这个:

module MyModule
   def analyze_log
     logfile = '/www/redmine/log/logfile.log'
     cat_cmd = "cat #{logfile}.0 #{logfile}"
     cat = IO.popen(cat_cmd)
     p cat.readlines
  end
end

我仍然看到为什么会有不同的行为。另外,为什么不使用File IO的文件类?

答案 2 :(得分:0)

更多Ruby方法是使用内部函数来处理这个问题:

module MyModule
  def analyze_log
    logfile = '/www/redmine/log/logfile.log'

    [
      "#{logfile}.0",
      logfile
    ].each do |file|
      File.readlines(file).each do |line|
        print line
      end
    end
  end
end

完全没必要运行子进程来读取文件。

相关问题