简体   繁体   English

Python:启动终端程序并在运行时解析其输出

[英]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. 我正在为流行的NodeJS服务器“ MeteorJS”编写Ubuntu的AppIndicator,该应用程序应列出可用项目并可以启动服务器,并且在启动服务器时,它将获取其Terminal输出并对它们做出反应。

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. 例如,当您更改代码时,它会输出"changed restarting..."或者当您再次更改"changed restarting... (2x)" ,这很好,但是当出现错误时,则会打印一些错误消息。

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. 我需要从python程序启动服务器,同时我可以对服务器在其标准输出上确切写出的输出做出反应。

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. 但这是我在后台运行bash脚本并在我感兴趣时获取其输出的方式。

# 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. 您可能想要一个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. 这是一个Python示例。 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. 它基本上类似于script(1),但带有可选时间戳的输出文件。 http://stromberg.dnsalias.org/~strombrg/pypty/ http://stromberg.dnsalias.org/~strombrg/pypty/

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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