【问题标题】:Returning a hash from a subprocess in Ruby using IO.popen使用 IO.popen 从 Ruby 中的子进程返回哈希
【发布时间】:2012-05-31 09:44:01
【问题描述】:

我在我的 Ruby 脚本中使用 IO.popen("cmd") 来运行 Ironruby 子例程。在我的 Ironruby 脚本中,我获取了一些数据并将其存储在哈希中。在我的 Ruby 脚本中,我使用 x=IO.popen("Iron ruby​​ script") 来检索哈希。问题是,我似乎无法让哈希显示在我的 Ruby 脚本中。我试过 x.gets、x.read 等。

使用 IO.popen 从该管道获取哈希的最佳方法是什么?

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby io popen


    【解决方案1】:

    在子进程中:

    require "yaml"
    puts YAML.dump(theHash)
    

    在父级中:

    require "yaml"
    x=IO.popen(...)
    theHash=YAML.load(x.read)
    

    【讨论】:

    • Marshall#dump 和 Marshal#load 比 YAML 快两个数量级。 x = {:a=>1,:b=>3.4, :c=>[1,2,3]}; N=1000; Benchmark.bm{|b| b.report{ N.times{Marshal.load(Marshal.dump(x))} }; b.report{ N.times{YAML.load(YAML.dump(x))} } } => 用户系统总实际 0.010000 0.000000 0.010000 ( 0.009638) 0.440000 0.140000 0.580000 ( 0.587589)
    • 好点,但我认为这是 MRI Ruby 到 IronRuby。它们根本不同,Marshal 被定义为版本和实现相关。 IronRuby 和 MRI Ruby 的任何两个版本具有相同 Marshal 格式的可能性非常低,可以认为是不可能的。
    • 好点回来了。我错过了这是跨越 ruby​​ 实现的细节。
    【解决方案2】:

    Ruby 附带 dRuby,一个用于 Ruby 的分布式对象系统。在这种情况下,这可能是矫枉过正。演示:

    #test1.rb
    require 'drb/drb' # in standard lib
    
    the_hash = Hash[:key1,'value1',:key2, 'value2']
    DRb.start_service("druby://localhost:8787", the_hash)
    DRb.thread.join
    
    
    #test2.rb
    require 'drb/drb'
    
    DRb.start_service
    p DRbObject.new_with_uri("druby://localhost:8787")
    #=>{:key1=>"value1", :key2=>"value2"}
    

    【讨论】:

      猜你喜欢
      • 2014-07-02
      • 2016-03-02
      • 2011-05-19
      • 2019-10-24
      • 1970-01-01
      • 2016-04-23
      • 2013-08-02
      • 2021-10-01
      • 1970-01-01
      相关资源
      最近更新 更多