天天看點

linux訓練python出現killed_再用 python 處理檔案的時候 程式運作過程中被 killed

情境描述

要處理一個目錄下所有的的日志檔案 xxx.log(每個檔案大概13G),過程是這樣的:檢索每行中是否包含 'xx-Obsever' 和 '大主宰' 這兩個詞,如果包含,則看這一行是否有'xx-Observer,[(.*)],recv',正則裡小括号中的内容是我想要的 id,如果比對到,則取出id,然後利用這個id去檢索 xxx.log 檔案中所有含有 [id] 的日志并輸出到 xxx.log.result 檔案

我的代碼

#!/usr/bin/env python

#coding=utf-8

import sys

import os

import re

import threading

import Queue

reload(sys)

sys.setdefaultencoding("gbk")

print 'start run'

queue = Queue.Queue(maxsize=0)

file_list = os.listdir('.')

for f in file_list:

if f.find('vropenhb') == -1:

continue

queue.put(f)

def handle_file():

while not queue.empty():

f = queue.get()

#file_dict = {'filename':f}

f1 = open(f,'r')

ids = set()

#for line in f1.readlines():

# if line.find('xx-Ob') != -1 and line.find(u'word=大主宰') != -1:

# print 'find one'

# res = re.search('xx-Observer,\[(.*)\],recv', line)

# if res != None:

# ids.add(res.group(1))

cmd_grep_ob = "grep xx-Ob " + f + " > ./search/" + f + ".search"

print cmd_grep_ob

os.system(cmd_grep_ob)

f1.close()

filename_search = './search/' + f + '.search'

f_search = open(filename_search,'r')

for line in f_search:

if line.find(u'大主宰') != -1:

res = re.search('xx-Observer,\[(.*)\],recv', line)

if res != None:

print 'find one'

ids.add(res.group(1))

f_search.close()

f_r = open(f, 'r')

output_filename = './result/' + f + '.result'

f_w = open(output_filename, 'w+')

for line in f_r.readlines():

res = re.search('xx-Observer,\[(.*)\],recv',line)

if res != None:

if res.group(1) in ids:

print 'write one'

f_w.write(line)

f_w.close()

f_r.close()

#for i in ids:

# file_dict['id'] = i

# cmd_grep_id = "grep %(id)s %(filename)s >> ./result/%(filename)s.result"

# cmd_grep_id = cmd_grep_id % file_dict

# os.system(cmd_grep_id)

mythread = []

for i in range(8):

t = threading.Thread(target=handle_file)

t.start()

mythread.append(t)

for t in mythread:

t.join()

問題描述:

最開始我是在 Python 中調用 grep 來完成整個過程的,但是發現很慢,但是沒有遇到 被 killed 的情況,是以我換成了檔案處理,通過 find 以及 正則 等方式來逐行處理,結果運作的時候發現,程式會經常卡住(剛開始跑就會卡住),過一會會繼續運作,然後過了一段時間 就被 killed 了,請問大家這是什麼原因,是不是我寫的多線程有問題,思路不對還是什麼原因,謝謝~

ps: 如果覺得情境和問題描述的不清晰,歡迎留言