0

我有一个我开发的 Ruby 脚本,它允许我安装和构建多个 C++ 包。我能够执行 Ruby 脚本并安装包而没有错误。

但是,我希望能够将所有输出(包括 cerr)捕获到我选择的“日志”文件中。我能够重定向 Ruby 的 cerr 和标准输出,但我无法捕获 bash 命令:qmake、、makemake installcerr。输出仍然流向终端。

我希望能够运行 Ruby 脚本并且看不到来自任何 、 或 bash 命令的任何调试消息qmakemakemake install能够稍后检查日志文件以获取构建结果。

4

4 回答 4

2

你可以做

require 'open3'

log = File.new("#{your_log_dir}/script.log", "w+")
command = "make"

Open3.popen3(command) do |stdin, stdout, stderr|
     log.puts "[OUTPUT]:\n#{stdout.read}\n"
     unless (err = stderr.read).empty? then 
          log.puts "[ERROR]:\n#{err}\n"
     end
end
于 2012-08-20T16:05:31.453 回答
0

将子进程的 stdout 和 stderr 直接转储到文件:

cmd = ['ls', '-ahl', '/my/directory'] # example directory listing
pid = Process.spawn *cmd, out: '/path/to/stdout/log', err: '/path/to/stderr/log'
Process.wait pid

您也可以传递文件描述符而不是路径字符串。

于 2012-08-20T16:22:35.393 回答
0

If you're on Mac OS or Linux, you can use standard redirection and a simple shell call if you want to capture the STDOUT and STDERR to a variable in your script:

asdf = `ls foo 2>&1`
asdf # => "ls: foo: No such file or directory\n"

2>&1 simply redirects STDERR in the command output to STDOUT, which is captured when the program runs.

If you want to redirect both STDOUT and STDERR to the same file for later, use:

`ls foo > output.log 2>&1`

The STDOUT has to be redirected before &2>1 will take effect, but that will capture both.

For more information see the "Redirect" section of man sh.

于 2012-08-20T18:13:29.637 回答
0

%x[#insert bash command here]捕获响应。如果您需要处理 STDERR,我相信您需要将其通过管道传输到 STDOUT。

于 2012-08-20T16:13:07.807 回答