Avba
Avba

Reputation: 15266

Ruby continuously output stdout of a long running shell command

How can I continuously output the results of a long running shell command, as the output becomes available?

Currently I need to do this (which I can only see after command has finished)

puts long_running_shell_command

What I want to do conceptually is

puts_immediately long_running_shell_command

Upvotes: 3

Views: 1190

Answers (2)

eiko
eiko

Reputation: 5345

My favorite way to work with shell commands is like so:

Open3.popen3 "shellcommand --args --more-args" do |stdin, stdout, stderr, thread|
  while line = stdout.gets
    puts line
  end
end

The command gives you input, output and error streams. You can call stdout.gets to get the next line of output (my favorite), or stdout.getc for the next character, if you really want immediacy. The function waits until input is available and then returns nil when the command completes, so a common technique is to wrap the command in a while-loop and have a set of commands repeatedly execute until the command completes.

Upvotes: 2

ndnenkov
ndnenkov

Reputation: 36101

Redirect the output to STDOUT:

# waits a second, prints the current directory's contents, waits 5 seconds
system('sleep 1; ls; sleep 5', out: STDOUT)

Upvotes: 4

Related Questions