Catching command-line errors using %x

后端 未结 4 1182
走了就别回头了
走了就别回头了 2021-01-11 13:16

Whenever you want to execute something on the command line, you can use the following syntax:

%x(command to run)

However, I want to catch a

4条回答
  •  情深已故
    2021-01-11 13:53

    Here's how to use Ruby's open3:

    require 'open3'
    include Open3
    
    stdin, stdout, stderr = popen3('date')
    stdin.close
    
    puts
    puts "Reading STDOUT"
    print stdout.read
    stdout.close
    
    puts
    puts "Reading STDERR"
    print stderr.read
    stderr.close
    # >> 
    # >> Reading STDOUT
    # >> Sat Jan 22 20:03:13 MST 2011
    # >> 
    # >> Reading STDERR
    

    popen3 returns IO streams for STDIN, STDOUT and STDERR, allowing you to do I/O to the opened app.

    Many command-line apps require their STDIN to be closed before they'll process their input.

    You have to read from the returned STDOUT and STDERR pipes. They don't automatically shove content into a mystical variable.

    In general, I like using a block with popen3 because it handles cleaning up behind itself.

    Look through the examples in the Open3 doc. There's lots of nice functionality.

提交回复
热议问题