9
與Getting output of system() calls in Ruby類似,我正在運行一個系統命令,但在這種情況下,我需要在命令運行時輸出STDOUT。如何在運行時獲得ruby系統()調用的STDOUT?
與Getting output of system() calls in Ruby類似,我正在運行一個系統命令,但在這種情況下,我需要在命令運行時輸出STDOUT。如何在運行時獲得ruby系統()調用的STDOUT?
至於在鏈接的問題,答案是再次不使用system
在system
不支持這一點。
但是這次的解決方案不是使用backticks
,而是IO.popen
,它返回一個IO對象,您可以使用它來讀取正在生成的輸入。
這裏是我的解決方案
def io2stream(shell, &block)
Open3.popen3(shell) do |_, stdout, stderr|
while line = stdout.gets
block.call(line)
end
while line = stderr.gets
block.call(line)
end
end
end
io2stream("ls -la", &lambda { |str| puts str })
這是奇怪的是,你應該做什麼特別的事情。根據我的經驗,當我使用`system`運行程序時,子程序的stdout轉到父程序的stdout,這似乎是你想要的。 – 2010-11-29 19:47:16
這也可能工作:http://stackoverflow.com/questions/2215455/printing-to-screen-in-a-rake-task/2215986#2215986 – 2010-12-06 17:19:31