Python:启动终端程序并在运行时解析其输出 [英] Python: start terminal program and parse its output while it's running

查看:41
本文介绍了Python:启动终端程序并在运行时解析其输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为流行的 NodeJS 服务器MeteorJS"编写 Ubuntu 和 AppIndicator,它应该列出可用的项目并可以启动服务器,当它启动服务器时,它会获取终端输出并对它们做出反应.

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.

当您启动meteor 时,它会根据发生的情况提供一些输出.例如,当您更改代码时,它输出 "changed restarting..." 或者当您再次更改 "changed restarting... (2x)" 时,这很好,但是当它出现错误时,它会打印一些错误消息.

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.

我的实际问题:

我需要从 python 程序启动服务器,同时我可以对服务器在 stdout 出现时写入的输出做出反应.

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.

所以我想

  • 打开终端程序
  • 将其发送到后台以便我完成我的工作
  • 对它打印的每一行做出反应

推荐答案

您可能希望研究线程化以下函数,然后弄清楚如何使其事件驱动".

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

但这就是我在后台运行 bash 脚本并在我对它感兴趣时获取它们的输出的方式.

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

这篇关于Python:启动终端程序并在运行时解析其输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆