[英]Looking for an efficient way to combine lines in Python
我正在編寫一個程序,以在Linux主機上聚合strace輸出行。 當strace使用“ -f”選項運行時,它將混合系統調用行,因此:
close(255 <unfinished ...>
<... rt_sigprocmask resumed> NULL, 8) = 0
<... close resumed> ) = 0
[pid 19199] close(255 <unfinished ...>
[pid 19198] <... rt_sigprocmask resumed> NULL, 8) = 0
[pid 19199] <... close resumed> ) = 0
我想遍歷輸出並將“未完成的”行與“恢復的”行合並。 因此,在上面的兩行輸出中:
close(255 <unfinished ...>
.....
<... close resumed> ) = 0
將合並為:
close(255) = 0
我當時正在考慮拆分“>”中的“未完成”行,並將其放入列表中。 如果將來的行包含簡歷,我將遍歷此列表以查看系統調用和pid是否存在。 如果它們是我將split()“>”處的行並將兩者合並。 好奇是否有更好的方法來做到這一點?
*更新*
感謝您的好評! 我提出了以下建議,希望對您的代碼有所了解:
holding_cell = list()
if len(sys.argv) > 1:
strace_file = open(sys.argv[1], "r")
else:
strace_file = sys.stdin
for line in strace_file.read().splitlines():
if "clone" in line:
print line
if "unfinished" in line:
holding_cell.append(line.split("<")[0])
elif "resumed" in line:
# Get the name of the system call / pid so we can try
# to match this line w/ one in the buffer
identifier = line.split()[1]
for cell in holding_cell:
if identifier in cell:
print cell + line.split(">")[1]
holding_cell.remove(cell)
else:
print line
有沒有更Python的方式來寫這個? 再次感謝您的好評!
一些迭代器(例如文件對象)可以嵌套。 假設您正在從類似文件的對象中讀取內容,則只需創建一個內部循環即可進行合並。 我不確定strace
日志的格式化規則是什么,但名義上可能是這樣的
def get_logs(filename):
with open('filename') as log:
for line in log:
if "<unfinished " in line:
preamble = line.split(' ', 1)[0].strip()
for line in log:
if " resumed>" in line:
yield "{}) = {}\n".format(preamble,
line.split('=')[-1].strip())
break
else:
yield line
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.