【问题标题】:How to execute a program and get the console's output? [duplicate]如何执行程序并获得控制台的输出? [复制]
【发布时间】:2012-06-18 08:08:18
【问题描述】:

可能重复:
Running a command from Ruby displaying and capturing the output

我必须在我的本地服务器上执行一个程序,并在一个变量中获取控制台的输出

【问题讨论】:

  • 你试过什么?你的代码在哪里?您收到了哪些错误消息?
  • 您要捕获哪些输出?其他程序的输出?

标签: ruby unix sinatra


【解决方案1】:
output = `echo "hello"`
puts output # => hello

【讨论】:

    【解决方案2】:

    您可以通过 IO 重新打开重定向输出。

    $stdout.reopen("stdout.txt", "w")
    $stderr.reopen("stderr.txt", "w")
    
    puts 'stdout redirect'
    warn 'stderr redirect'
    

    【讨论】:

      【解决方案3】:
      $ irb
      1.9.3p125 :001 > cal = %x[/usr/bin/cal]
      1.9.3p125 :002 > puts cal
           June 2012        
      Su Mo Tu We Th Fr Sa  
                      1  2  
       3  4  5  6  7  8  9  
      10 11 12 13 14 15 16  
      17 18 19 20 21 22 23  
      24 25 26 27 28 29 30  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-12
        • 1970-01-01
        • 1970-01-01
        • 2019-09-10
        • 1970-01-01
        • 2011-06-24
        相关资源
        最近更新 更多