我使用python内置的socket和多处理库来扫描主机的tcp端口。我知道我的第一个函数可以工作,我只是想让它与multriprocess Queue和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)
我只想打印出开放的端口号。因为它正在扫描谷歌网站它实际上应该只返回80
和443
。你知道吗
编辑:如果我使用Pool,这会起作用,但我转到Process and Queue是因为其中较大的部分在Django中运行,带有芹菜,并且在使用Pool执行时不允许守护进程
对于这样的工作,
multiprocessing.Pool
将是更好的处理方法。你知道吗您不必担心创建进程和队列;所有这些都是在后台为您完成的。worker函数只需返回一个结果,它将为您传输到父进程。你知道吗
我建议使用
multiprocessing.Pool.imap_unordered()
,因为它一可用就开始返回结果。你知道吗一件事;worker进程只接受一个参数。如果每个调用需要多个不同的参数,请将它们包装成一个元组。 如果所有调用的参数都相同,请使用
functools.partial
。你知道吗更现代的方法是使用来自
concurrent.futures
的Executor.map()
方法。因为您的工作主要由套接字调用组成,所以我认为您可以在这里使用ThreadPoolExecutor
。这应该比ProcessPoolExecutor
稍微少一点资源密集型。你知道吗相关问题 更多 >
编程相关推荐