Python: start terminal program and parse its outpu

2019-08-03 06:57发布

问题:

I am writing and AppIndicator for Ubuntu for the Popular NodeJS Server "MeteorJS" that should list the available projects and could start the server and when it started the server, it gets its Terminal outputs and reacts to them.

When you start meteor it gives some output depending on what happens. For example when you change your code, it outputs "changed restarting..." or when you change again "changed restarting... (2x)" that is fine, but when it has an error it prints some error message.

That is fine unless you have not enough space on your desktop to see that terminal.

so I write an application that should notify me in another way about those messages.

My Actual Problem:

I need to start the server from a python program while i can react on the output the server writes on its stdout exactly when it appears.

So I want to

  • Open a Terminal Program
  • Send it to background so that I can do my job
  • React to every line it prints

回答1:

You may want to look into threading the below function and then figuring out how to make it "event driven".

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

# 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


回答2:

You likely want a pty. It can receive output from the application, and you can read from it and do with it what you want.

Here's a Python example. It just records everything to a file and sends it to the terminal. It's basically like script(1), but with optionally timestamped output files. http://stromberg.dnsalias.org/~strombrg/pypty/

HTH