python - 当术语在 bash 中显示时终止终端应用程序

标签 python linux bash

是否可以编写一个运行 python 应用程序的 bash 脚本,直到应用程序的输出显示指定的术语,然后关闭应用程序?

编辑: 输出看起来像这样:

2017-11-11 14:21:27 LOG: 192.168.0.1 - Administrator:Test54
2017-11-11 14:21:28 LOG: 192.168.0.1 - Administrator:Test55
2017-11-11 14:21:29 LOG: 192.168.0.1 - Administrator:Test56
2017-11-11 14:21:30 LOG: 192.168.0.1 - Administrator:Test57
2017-11-11 14:21:31 LOG: 192.168.0.1 - Administrator:Test58
2017-11-11 14:21:32 LOG: 192.168.0.1 - Administrator:Test59
2017-11-11 14:21:33 LOG: 192.168.0.1 - Administrator:Test60
2017-11-11 14:21:34 LOG: 192.168.0.1 - Administrator:Test61
2017-11-11 14:21:35 LOG: 192.168.0.1 - Administrator:Test62
2017-11-11 14:21:35 SUCCESS : 192.168.0.1 - Administrator:Test62

它应该在 SUCCESS 出现后关闭。

最佳答案

假设您有以下 Python 程序:

#!/usr/bin/python
for i in range(0,5001):
    print(i)

当它像这样输出 2500 时,您可以终止它:

stdbuf -oL python a.py | sed '/2500/q'

注意,这有点脏,你可能会收到一个

Traceback (most recent call last):
  File "a.py", line 2, in <module>
    print(i)
BrokenPipeError: [Errno 32] Broken pipe

但是如果你想杀掉这个程序......


重要提示:

如果脚本正在写入 stderr(就像 logging.StreamHandler 默认情况下那样),或者如果它正在处理 BrokenPipeError,这将不起作用。前者可以很容易地用 |& 重定向修复,但在后一种情况下, kill -INT 会更好。

关于python - 当术语在 bash 中显示时终止终端应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47238161/

相关文章:

c - strtok 没有遍历所有标记

java - 使用 JSch Ssh 到远程机器,要求两次输入用户名和密码

linux - 如果输入的第一行包含字符串,我如何使用 sed 或 grep 删除它?

python - 在 Keras 中使用 tf.metrics?

python - 对 numpy 步幅的困惑

linux - 详细收听文件更改

bash - 如何为 bash 子文件夹中的所有文件运行 dos2unix?

bash - 从命令行覆盖 Bash 脚本中的变量

python - 制作聊天客户端窗口

Python:将函数输出关联到字符串,然后组合成字典