Catching command-line errors using %x

后端 未结 4 1157
走了就别回头了
走了就别回头了 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:33

    You need a mix of @Cam 's answer and @tonttu 's answer.

    decent explanation of $? and others.

    Edit: the domain http://blog.purifyapp.com is now in hands of a domain-squatter and scammer.

    result = %x(command to run 2>&1)
    
    unless $? == 0 #check if the child process exited cleanly.
        puts "got error #{result}"
    end
    
    0 讨论(0)
  • 2021-01-11 13:45

    You might want to redirect stderr to stdout:

    result = %x(command to run 2>&1)
    

    Or if you want to separate the error messages from the actual output, you can use popen3:

    require 'open3'
    stdin, stdout, stderr = Open3.popen3("find /proc")
    

    Then you can read the actual output from stdout and error messages from stderr.

    0 讨论(0)
  • 2021-01-11 13:46

    So this doesn't directly answer your question (won't capture the command's output). But instead of trying begin/rescue, you can just check the exit code ($?) of the command:

    %x(command to run)
    unless $? == 0
       "ack! error occurred"
    end
    

    Edit: Just remembered this new project. I think it does exactly what you want:

    https://github.com/envato/safe_shell

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题