【问题标题】:Get error output of a system call?获取系统调用的错误输出?
【发布时间】:2012-02-21 02:04:34
【问题描述】:

当我执行以下操作时:

output = `identify some_file`
output == "Output of identify"

但是当...

output = `identify non_existant_file`
output != "Error output of identify"

如何获取系统调用的错误输出?

【问题讨论】:

    标签: ruby bash system


    【解决方案1】:

    您可以使用Open3.popen3

    http://www.ruby-doc.org/stdlib-1.9.3/libdoc/open3/rdoc/Open3.html#method-c-popen3

    popen3(*cmd, &block) 点击切换源

    打开 stdin、stdout 和 stderr 流并启动外部可执行文件。

    Open3.popen3([env,] cmd... [, opts]) {|stdin, stdout, stderr, wait_thr|
      pid = wait_thr.pid # pid of the started process.
      ...
      exit_status = wait_thr.value # Process::Status object returned.
    }
    

    【讨论】:

      【解决方案2】:

      我找到了答案。输出被发送到 stderr。所以我可以在命令末尾添加以下内容,将 stderr 重定向到 stdout:

      output = `identify any_file 2>&1`
      output == "Error or output of identify"
      

      Here is the explanation of this witchcraft

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-27
        • 2016-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        • 2021-09-16
        相关资源
        最近更新 更多