1

I'm developing a webbased controller for robots. When I run a command like os.system('cd /home/tim/tmprcc/; ino build; ino upload'), I need to be able to send the output to the web app. How do I capture the output during execution in Python? The user needs to be able to see the output live as it is showing on my terminal.

Your answer should have Python code that calls do_something_function(new_output) every time a line of output appears, where new_output is the entire output generated so far.

Nathan
  • 4,009
  • 2
  • 20
  • 21
Timothy Clemans
  • 1,711
  • 3
  • 16
  • 26
  • The design of the web is not amenable to real-time updates. Unless you dive into AJAX and COMET techniques. However, now you can try WebSocket and that might work out,but you'll have to write some Javascript too. – Keith Nov 29 '12 at 00:39
  • 2
    `os.system` will send the output of the command to `sys.stdout` and/or `sys.stderr`, use [`subprocess.Popen`](http://docs.python.org/2/library/subprocess.html#subprocess.Popen) instead. – Andrew Clark Nov 29 '12 at 00:42
  • Keith, I'm using Ajax. F.J. it would have to been nice to see some example code. I updated my question to mention this. – Timothy Clemans Nov 29 '12 at 00:55
  • [This question](http://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line) may also be useful (see accepted answer). It even has some example code. :-) – Sam Mussmann Nov 29 '12 at 01:07

1 Answers1

0

You're going to want to look into the subprocess module.

import subprocess

cmd = subprocess.Popen(['cd', '/home/time/tmprcc;', 'ino', 'build;',
                        'ino', 'upload;'], stdout=subprocess.PIPE)

while cmd.poll() is None:
    new_output = cmd.stdout.readline()
    do_something_function(new_output)

Keep in mind that there are some caveats to this method. Straight from subprocess's documentation:

Warning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

See this answer for more info.

Community
  • 1
  • 1
Nathan
  • 4,009
  • 2
  • 20
  • 21