Reputation: 3402
Suppose I have a method which computes hard problems (maybe a depth-first search in a huge graph), we can call this method dfs(graph)
.
This method also output to stdout
each result reached, using puts result
.
def dfs(graph)
while true
# lots of computation
result = something_reached
puts result
end
end
I want to display a progressbar in shell to show that computation is running, so I add an instance like this:
pbar = ProgressBar.create(title: "Computing", starting_at: 1, total: nil)
and progressbar status must be updated (pbar.increment
) as computation is running.
In a shell, I execute my program like this:
ruby dfs.rb > dfs_results.txt
Issues:
With pbar
is flushed to stdout
so prograss-bar is redirected to dfs_results.txt
and computation results are not store in this file.
Without pbar
result data is stored in file as is expected, but obviously without progress-bar.
I know that results could be stored with File.open
usage, but it is desirable done with shell redirections.
Question:
How should I be implemented to flush computation resulta to dfs_results.txt
file and show a progress-bar to keep a executing progress for user?
Upvotes: 2
Views: 761
Reputation: 106882
Just open a file to log into:
log = File.open('dfs_results.txt', 'w')
# write into log file
log.write(result)
And your progressbar still writes to stdout. When you open a second screen you can follow the output with:
tails -f dfs_results.txt
Update: Or you can use stdout for the progressbar and stderr for the output of the script. Instead of puts result
write:
$stderr.puts results
and start the script with:
ruby dfs.rb 2> dfs_results.txt
I still think the first version is better because results are not errors...
Upvotes: 1