From: Forrest Chang Date: 2005-08-13T07:41:11+09:00 Subject: Re: interactively processing a line at a time "Ara.T.Howard" writes: HI Ara: That did the trick. Thanks. BTW, nice article on Grids w/RUby and SQLite Forrest > On Sat, 6 Aug 2005, Forrest Chang wrote: > >> HI All: >> >> For the following code segement running on win32 ruby (1 click installer) >> >> sout = IO.popen( "output"); >> while( line = sout.gets) >> do_something_with( line) >> end >> >> >> If for example, "output" printed out something 5 times every second, >> then on the command line, I would see something printed out every >> second, 5 times. Running through the above code, I would not see >> anything until after 5 secs, which I assume that after the program >> exits, the output is flushed, and then it would be all 5 entries. I >> ran the same sort of code successfully solaris, so I expected it to >> work on windows. >> >> I did an experiment, and wrote a ruby program that printed a >> line then flushed STDOUT, paused, repeated, etc., and it works as >> suspected. Since I do not have control over the actual "output" >> program, how can I get it so that each line is flushed? sout.sync = >> true didn't work (I imagine it only works if I write to sout) >> >> Any ideas? > > try this - it should/might work on windoze - i assume it inherits open file > handles from the parent. i ran it on xp and it seemed fine: > > harp:~ > ruby a.rb > [Fri Aug 05 20:49:51 MDT 2005, "42\n"] > [Fri Aug 05 20:49:56 MDT 2005, "42\n"] > [Fri Aug 05 20:50:01 MDT 2005, "42\n"] > [Fri Aug 05 20:50:06 MDT 2005, "42\n"] > [Fri Aug 05 20:50:11 MDT 2005, "42\n"] > ... > ... > ... > > > harp:~ > cat a.rb > require 'tempfile' > > def popen_sync cmd > tf = Tempfile::new $PROGRAM_NAME > tf.puts <<-ruby_code > STDOUT.sync = true > exec STDIN.read > ruby_code > tf.close > > sync_cmd = "ruby #{ tf.path }" > pipe = IO::popen sync_cmd, 'r+' > pipe.puts cmd > pipe.close_write > pipe > end > > output = "ruby -e 'loop{ p 42; sleep 5}'" > sout = popen_sync output > > while(line = sout.gets) > p [Time::now, line] > STDOUT.flush > end > > > again - this will only work if exce inherits open files and there properties... > > hth. > > -a > -- > =============================================================================== > | email :: ara [dot] t [dot] howard [at] noaa [dot] gov > | phone :: 303.497.6469 > | My religion is very simple. My religion is kindness. > | --Tenzin Gyatso > ===============================================================================