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

2024-03-28 23:05:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的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”这个数字。我想用一些东西来帮助我调整无法提供的键的数量,并将其用作脚本中的变量


1条回答
网友
1楼 · 发布于 2024-03-28 23:05:10

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

$ 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 $2 } /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

相关问题 更多 >