我正在使用python的内置套接字和多处理库来扫描主机的tcp端口。我知道我的第一个功能可以正常工作,而我只是想使其与multriprocess Queue and Process一起工作,而不知道哪里出了问题。
如果我删除了Queue
一切似乎都已完成,则实际上只需要从中获取结果即可。
from multiprocessing import Process, Queue
import socket
def tcp_connect(ip, port_number):
try:
scanner = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scanner.settimeout(0.1)
scanner.connect((str(ip), port_number))
scanner.close()
#put into queue
## Remove line below if you
q.put(port_number)
except:
pass
RESULTS = []
list_of_numbs = list(range(1,501))
for numb in list_of_numbs:
#make my queue
q = Queue()
p = Process(target=tcp_connect, args=('google',numb))
p.start()
#take my results from my queue and append to a list
RESULTS.append(q.get())
p.join()
print(RESULTS)
我只想打印出打开的端口号。现在,由于它正在扫描google.com,因此它实际上应该只返回80
和443
。
编辑:如果我使用Pool,但去了Process and Queue,这会起作用,因为其中较大的部分在Django中使用celery运行,并且在使用Pool执行时不允许守护程序 < / p>
答案 0 :(得分:0)
对于这样的工作,multiprocessing.Pool
将是处理它的更好方法。
您不必担心创建流程和队列;所有这些都在后台为您完成。您的worker函数只需要返回一个结果,该结果将为您传输到父进程。
我建议使用multiprocessing.Pool.imap_unordered()
,因为它会在可用时立即开始返回结果。
一件事;工作进程仅接受一个参数。每个调用都需要多个不同的参数。将它们包裹在一个元组中。
如果所有调用的参数都相同,请使用functools.partial
。
一个更现代的方法是使用Executor.map()
中的concurrent.futures
方法。我认为,由于您的工作主要由套接字调用组成,因此您可以在此处使用ThreadPoolExecutor
。这应该比ProcessPoolExecutor
少一些资源。