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

Ruby 为什么我的代码在irb中工作,而不是从脚本中工作?,ruby,redmine,popen,Ruby,Redmine,Popen,我想对Redmine日志文件进行一些分析,包括以前的日志。因此,我想连接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.read

我想对Redmine日志文件进行一些分析,包括以前的日志。因此,我想连接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中执行此操作时,没有模块和方法定义的代码可以很好地工作,但在同一台机器上,当我将代码包装到模块MyModule中的方法analyze_日志中并从脚本调用此代码时,它不工作,不打印行,如下所示:

#!/opt/ruby/bin/ruby
require './my_module'
include MyModule
analyze_log
有什么好处

顺便说一句,如果有更好的方法在同一个循环中顺序处理多个文件,我很高兴听到这个消息。但我主要担心的是,它在irb中工作,但在作为脚本运行时不起作用

我正在以运行irb的用户身份运行脚本。

尝试更改:

cat = IO.popen(cat_cmd)
致:

或者将循环更改为在行上迭代:

cat = IO.popen(cat_cmd)
cat.readlines.each {|line| puts line }
你试过这个吗:

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

我仍然明白为什么会有不同的行为。还有,为什么不为文件IO使用file类呢?

一种更为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

运行子进程读取文件是完全不必要的。

以什么方式不起作用?请发布你所有的代码,包括模块代码。你说不工作是什么意思?运行脚本时会发生什么?我修改了帖子以添加额外的代码。当我说“不工作”时,我的意思是没有打印任何行。更改需要相对。普华永道显然不在这条路上。那样做了,没什么区别。我知道它正在寻找模块,因为如果我加上“你好!”为了分析日志,它会这样做。就这点而言,我知道它正在创建IO对象,因为如果我在创建cat的行之后添加p cat,它会打印。它似乎是空的,与我在irb中执行相同步骤时相反。当您使用cat=IO.opencat_cmd中的cat.readlines获取行时,ruby返回一个行数组而不是字符串。为了使用IO.popen运行代码,需要将循环更改为cat.readlines。每个{line | put line}exec实际上会切换进程并结束Ruby。执行官的电话打不通了。在不使用execWorks的情况下,有一些.编辑代码来提出一个解决方案,这非常完美,而且更加优雅。谢谢
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