我如何从 python 中读取特定的终端输出作为另一个脚本中的输入

How can i read a particular terminal output from python as input in another script

我有python这样的脚本输出

client:"A"
Total number of keys discovered: 22
Execution finished. Total time: 0:00:05.361506
Key: 'caJ8ArNRvefgdfgbdhfdbfdbf' | Cannot flip key due to  
feature1 being enabled
Key: 'caixF0Nmdfjdfdbfdgdbgdnmjdfs' | Cannot flip key due to  
feature1 being enabled
Total keys: 22 | Keys that Application can serve: 20 | Keys that Application can't serve: 2
Execution finished. Total time: 0:00:33.796226
client:"B"
Total number of keys discovered: 13
Execution finished. Total time: 0:00:05.539271
Total keys: 13 | Keys that Application can serve: 13 | Keys that Application can't serve: 0
Execution finished. Total time: 0:00:20.573984

我想在 python 脚本中使用“应用程序无法提供的密钥:2”这个数字我想要一些东西来帮助我 grep 无法提供的密钥数量并将其用作我脚本中的一个变量

假设您将该输出作为文本文件。

$ cat output.txt
# client:"A"
# Total number of keys discovered: 22
# Execution finished. Total time: 0:00:05.361506
# Key: 'caJ8ArNRvefgdfgbdhfdbfdbf' | Cannot flip key due to  
# feature1 being enabled
# Key: 'caixF0Nmdfjdfdbfdgdbgdnmjdfs' | Cannot flip key due to  
# feature1 being enabled
# Total keys: 22 | Keys that Application can serve: 20 | Keys that Application can't serve: 2
# Execution finished. Total time: 0:00:33.796226
# client:"B"
# Total number of keys discovered: 13
# Execution finished. Total time: 0:00:05.539271
# Total keys: 13 | Keys that Application can serve: 13 | Keys that Application can't serve: 0
# Execution finished. Total time: 0:00:20.573984

然后你可以使用awk和运行这一行来得到你想要的输出。

awk 'BEGIN { FS = ":" } /client/ { print  } /serve/ { print $NF }' output.txt > client.txt
cat client.txt
# "A"
#  2
# "B"
#  0

然后您可以使用 client.txt 文件并将其读入 Python,类似这样。

with open('client.txt') as fh:
    for line in fh.readlines():
        print(line.replace('\"', '').strip())
# A
# 2
# B
# 0