Python: run a terminal program and parse its output while running

I am writing and AppIndicator for Ubuntu for the popular NodeJS server "MeteorJS" which has to list the available projects and start the server and when it starts the server it gets its terminal outputs and responds to them.

When you start a meteor, it gives some effect depending on what happens. For example, when you change your code, it outputs "changed restarting..."

or when you change again "changed restarting... (2x)"

, that's ok, but when it has an error, it outputs an error message.

It's ok if you don't have enough desktop space to see this terminal.

so I am writing an application that needs to notify me differently about these messages.

My actual problem:

I need to start the server from a python program as long as I can respond to the output that the server writes to its stdout exactly when it appears.

So I want

  • Open a terminal program
  • Send it to the background so I can do my job.
  • React on every line printed

source to share

2 answers

You might want to take a look at the threaded function below and then figure out how to make it "event driven".

But this is how I run bash scripts in the background and get their output when I'm interested.

# To test it out, run the script and then turn your wifi off and on.

import subprocess

def tail():
    command = ["tail", "-f", "/var/log/wifi.log"] # your bash script execute command goes here
    popen = subprocess.Popen(command, stdout=subprocess.PIPE)
    for line in iter(popen.stdout.readline, ""):
        yield line,

logger = tail()

for line in logger:
    print line




You probably want pty. It can receive output from the application, and you can read it and do whatever you want with it.

Here's a Python example. It just writes everything to a file and sends it to the terminal. It's basically like script (1), but with optional temporary output files.




All Articles