Capturing the output of an external program line by line

A

Aditya Mahajan

Hi,

I want to run an external program in ruby. The external program takes
a long time to execute. While running, it gives the information on
stdout about what it is doing. How can I run the external program
inside ruby so that I can capture this information, and display it on
stdout? I tried %x{...}, `...` and system("...."), but all of them
give me a result AFTER the external program has finished executing,
not during its execution.

Thanks,
Aditya
 
M

Markus Schirp

Am Mon, 15 Oct 2007 04:23:41 +0900
schrieb Aditya Mahajan said:
Hi,

I want to run an external program in ruby. The external program takes
a long time to execute. While running, it gives the information on
stdout about what it is doing. How can I run the external program
inside ruby so that I can capture this information, and display it on
stdout? I tried %x{...}, `...` and system("...."), but all of them
give me a result AFTER the external program has finished executing,
not during its execution.

Thanks,
Aditya

in,out = IO.popen($command)

in refers to standart input of the program
out to the standart output

you can receive lines from the program using in.gets. Beware, "in" may
be a reserved word in ruby.
 
T

Tim Hunter

Aditya said:
Hi,

I want to run an external program in ruby. The external program takes a
long time to execute. While running, it gives the information on stdout
about what it is doing. How can I run the external program inside ruby
so that I can capture this information, and display it on stdout? I
tried %x{...}, `...` and system("...."), but all of them give me a
result AFTER the external program has finished executing, not during its
execution.

Thanks,
Aditya
I've been using this:

IO.popen("#{cmd} 2>&1") do |f|
while line = f.gets do
# do whatever you want with line
end
end

Note that this gets both stdout and stderr.
 
A

Aditya Mahajan

Tim said:
I've been using this:

IO.popen("#{cmd} 2>&1") do |f|
while line = f.gets do
# do whatever you want with line
end
end

Note that this gets both stdout and stderr.

Thank you Tim and Markus. Both your methods work perfectly. Since I just
needed to capture the program's output, I am using Tim's method.

Thanks,
Aditya
 
M

mortee

Markus said:
in,out = IO.popen($command)

in refers to standart input of the program
out to the standart output

Are you absolutely sure IO.popen returns an array of two IOs?

mortee
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top