रूबी में, $stderr
, उत्पादन धारा है कि है वर्तमान में stderr के रूप में इस्तेमाल करने के लिए संदर्भित करता है, जबकि STDERR
डिफ़ॉल्ट stderr धारा है। $stderr
पर अस्थायी रूप से एक अलग आउटपुट स्ट्रीम असाइन करना आसान है।
require "stringio"
def capture_stderr
# The output stream must be an IO-like object. In this case we capture it in
# an in-memory IO object so we can return the string value. You can assign any
# IO object here.
previous_stderr, $stderr = $stderr, StringIO.new
yield
$stderr.string
ensure
# Restore the previous value of stderr (typically equal to STDERR).
$stderr = previous_stderr
end
अब आप निम्न कर सकते हैं:
captured_output = capture_stderr do
# Does not output anything directly.
$stderr.puts "test"
end
captured_output
#=> "test\n"
इसी सिद्धांत भी $stdout
और STDOUT
के लिए काम करता है।
require "stringio"
def capture_stderr
real_stderr, $stderr = $stderr, StringIO.new
yield
$stderr.string
ensure
$stderr = real_stderr
end
इसे और अधिक संक्षेप में बहुत थोड़ा StringIO का उपयोग करता है, और $ से पहले capture_stderr बुलाया गया था जो कुछ भी यह था के रूप में stderr को बरकरार रखता है:
संबंधित प्रश्न: http://stackoverflow.com/questions/3018595/how-do लेकिन आप एक बाहरी प्रक्रिया बुला रहे हैं, और
$stderr = StringIO.new
काम नहीं करता है, तो आप को stderr बाहर एक अस्थायी फ़ाइल के लिए लिख सकते हैं -i-redirect-stderr-and-stdout-to-file-for-a-ruby-script –