我有一个python脚本,所以我在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运行(个体): 分贝= MySQLdb.connect( '本地主机', 'MYTABLE', '用户', 'MYTABLE') 光标= db.cursor() 查询=“挖+短“+ str(reverse_ip)+”。“ +键 尝试: 输出= subprocess.check_output(查询,壳=真) 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 ip_client(range_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值没有执行(不插入到数据库中,但也有一些关键的,VALU执行多次)。我的字典有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]
尽管此代码可能会帮助解决问题, 提供关于_why_和/或_how_ it 的附加上下文回答该问题将显着提高其长期价值 。请[编辑]你的答案,添加一些 的解释。 –
我试过了,但不能附加没有启动的线程。 –
非常感谢,我按照你的代码解决了我的问题。确切地说,只需定义一个函数,不需要使用类方法。我将在上面发布我的编辑代码。 –