[英]Python threading did not execute all threads which created
我有一个python脚本,因此我在python中使用线程模块来并发执行。
class check_bl(threading.Thread):
def __init__(self, ip_client, reverse_ip, key, value):
threading.Thread.__init__(self)
self.ip_client = ip_client
self.reverse_ip = reverse_ip
self.key = key
self.value = value
def运行(自):db = MySQLdb.connect('localhost','mytable','user','mytable')游标= db.cursor()查询=“ dig + short” + str(reverse_ip)+“。 ” +键尝试:输出= subprocess.check_output(query,shell = True)output_edited = output.strip()除外:output_edited =“发生超时”
if output_edited in value:
try:
cursor.execute() # execute INSERT command
db.commit()
except:
db.rollback()
db.close()
else:
try:
cursor.execute() # execute INSERT command
db.commit()
except:
db.rollback()
db.close()
对于IPNetwork(range_ip_client)中的ip_client:ip_client = .... reverse_ip = ...
for key, value in my_dictionary.items():
myThread = check_bl(ip_client, reverse_ip, key, value)
myThread.start()
threadList.append(myThread)
for t in threadList:
t.join()
问题是my_dictionary中的每个键都没有执行值(不能插入数据库,尽管某些键值执行了多次)。 我的词典有30个项目,但其中只有10-20个项目可以执行。 如果我像下面的2个示例一样插入join(),则我的所有字典item()都将执行,但同时只有一个线程执行。 每个创建的线程都有问题吗,它会创建数据库连接。 因此数据库无法处理它。
for key, value in my_dictionary.items():
myThread = check_bl(ip_client, reverse_ip, key, value)
myThread.start()
threadList.append(myThread)
for t in threadList:
t.join()
要么
for key, value in my_dictionary.items():
myThread = check_bl(ip_client, reverse_ip, key, value)
myThread.start()
t.join()
谢谢Dksj,我的问题解决了。 类方法可能有问题,只需要定义一个函数即可。
def check_bl(ip_client, reverse_ip, key, value):
db = MySQLdb.connect('localhost', 'mytable', 'user', 'mytable')
cursor = db.cursor()
query = "dig +short " + str(reverse_ip) + "." + key
try:
output = subprocess.check_output(query, shell=True)
output_edited = output.strip()
except:
output_edited = "Timeout occured"
if output_edited in value:
try:
cursor.execute() # execute INSERT command
db.commit()
except:
db.rollback()
db.close()
else:
try:
cursor.execute() # execute INSERT command
db.commit()
except:
db.rollback()
db.close()
for ip_client in IPNetwork(range_ip_client):
ip_client = ....
reverse_ip = ...
for key, value in my_dictionary.items():
myThread = check_bl(ip_client, reverse_ip, key, value)
threadList.append(myThread)
[t.start() for t in threadList]
[t.join() for t in threadList]
我的问题与您的问题略有不同,并且我没有使用类方法,我只是根据我的经验修改了您的代码,您可以尝试一下。 该链接帮助我解决了我的问题: 如何在Python中使用线程?
def check_bl(ip_client,reverse_ip,键,值):....
threads []
for key, value in my_dictionary.items():
# Instantiates the thread
myThread = Thread( target=check_bl, args=(ip_client, reverse_ip, key, value) )
#add thread to list
threads.append(myThread)
[th.start() for th in threads]
#Join all the threads to make sure the parent waits for all of them to finish
[th.join() for th in threads]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.