在Popen中合并stdout和stderr [英] Merge stdout and stderr in Popen

查看:131
本文介绍了在Popen中合并stdout和stderr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby的popen/spawn中,如何将STDOUT和STDERR合并为单个流而又不使用>2&1?

In Ruby's popen/spawn, how do I merge both STDOUT and STDERR as a single stream wihthout resorting to using >2&1?

在Python中,这将是:

In Python, this would be:

>>> import subprocess
>>> subprocess.check_output('my_prog args', stderr=subprocess.STDOUT, shell=True)

请注意stderr参数.

我使用Open3 -因为我不想 just stdout-但它已经将它们分为两个流.

I use Open3 - as I don't want just stdout - but it already separates them into two streams.

推荐答案

使用您的

Using the code from your other question, here you go:

cmd = 'a_prog --arg ... --arg2 ...'
Open3.popen2({"MYVAR" => "a_value"}, "#{cmd}", {:err => [:child, :out]}) { |i,o|
  # This output should include stderr as well
  output = o.read()
  repr = "$ #{cmd}\n#{output}"
}

一些更改:

  1. popen2的第三个参数会将stderr重定向到stdoutl.请注意,它必须是生成的进程的标准输出,而不是系统范围的标准输出,因此您需要指定:child:out
  2. 您需要使用.popen2而不是.popen3,因为如果为stderr包含第三个e选项,则似乎忽略了重定向
  3. 由于您使用的是.popen2,因此只能将|i,o|传递给块:
  1. The third parameter to popen2 will redirect stderr to stdoutl. Note that it needs to be the spawned process's stdout, not the system-wide stdout, so you need to specify :child's :out
  2. You need to use .popen2 instead of .popen3 as it seems the redirection is ignored if you include the 3rd e option for stderr
  3. Because you're using .popen2, you only pass |i,o| to the block:

这篇关于在Popen中合并stdout和stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆