我需要修改list
,通过在线程末尾添加一些元素。如何修改线程内的列表?
这是我的代码:
def go():
while queueCommand.qsize() > 0:
command = queueCommand.get(False)
res = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)
output = res.communicate()
output = str(output)
star = output.find("address") + 8
en = output.find(",")
ip = output[star:en-3]
alist.append(ip) #<================== her i use the liste
if __name__ == '__main__':
with open ("icq.txt","r") as myfile:
text = myfile.read()
end = 0
alist = []
queueCommand = Queue.Queue()
while True:
start = text.find("href=") + 13
if start == 12:
break
end = text.find("/",start)
if text[start:end].find("icq.com") != -1:
hostname="host "+ text[start:end]
queueCommand.put(hostname)
text = text[end:len(text)]
for i in range(10):
threading.Thread(target=go,args=(alist)).start() #<====== i give the list as argument
print alist
最后一个print语句显示一个空的列表,[]
。有任何想法吗?
你需要有一些同步,可能与互斥体。 –
我可以有一个使用哑巴的例子,我很抱歉,但我是新的python – user3383192
地方alist = []之外的main,在你的go()函数之上,然后在main中使用它。我建议你在实例化队列时做同样的事情; queueCommand = Queue.Queue()。如果在线程类中使用它并定义一个单独的函数来读取文件,它可能会更容易。这是一个链接到一个可能是有用的SO答案http://stackoverflow.com/questions/6286235/multiple-threads-in-python – user1749431