简体   繁体   中英

Python: start terminal program and parse its output while it's running

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM