【发布时间】:2016-07-14 13:53:23
【问题描述】:
我有一个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
定义运行(自我): db = MySQLdb.connect('localhost', 'mytable', 'user', 'mytable') 游标 = db.cursor() 查询=“挖掘+短”+ str(reverse_ip)+“。” + 键 尝试: 输出 = subprocess.check_output(查询,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 中的 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 中的每个键、值都没有执行(不是 INSERT 到数据库,虽然一些键、值执行了多次)。 我的字典有 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 multithreading python-2.7