Python处理计数器更新
我正在使用python多处理来调用一个名为“sql_fetch”的函数,该函数应该更新变量计数,就像它在我的列表(即“test_propid_entid”)上迭代的次数一样,以确定我从查询中获得好数据的次数。如果我的函数调用生成了查询,并且我只想在多处理调用结束时将结果打印在count变量中,以确定dataframe返回结果的次数(即查询返回记录的次数):我如何实现这一点?count总是为我打印1,因为它会在每次调用时重置值 我在多处理中使用了以下方法:Python处理计数器更新,python,multiprocessing,python-multiprocessing,Python,Multiprocessing,Python Multiprocessing,我正在使用python多处理来调用一个名为“sql_fetch”的函数,该函数应该更新变量计数,就像它在我的列表(即“test_propid_entid”)上迭代的次数一样,以确定我从查询中获得好数据的次数。如果我的函数调用生成了查询,并且我只想在多处理调用结束时将结果打印在count变量中,以确定dataframe返回结果的次数(即查询返回记录的次数):我如何实现这一点?count总是为我打印1,因为它会在每次调用时重置值 我在多处理中使用了以下方法: from tqdm import tqd
from tqdm import tqdm
start_dt = time()
multi =[]
with tqdm(total=len(test_propid_entid)) as pbar:
for sub_prop_entid in test_propid_entid:
t_sub = multiprocessing.Process(target=sql_fetch, args=(sub_prop_entid,))
pbar.update()
multi.append(t_sub)
t_sub.start()
for a in multi:
a.join()
print('TOTAL TIME: ' ,time() - start_dt)
我想调用sql_fetch函数从Oracle查询引擎获取数据:
import pandas as pd
def sql_fetch(sub_prop_entid):
count = 0
data= pd.read_sql(query_randomizer(
sub_prop_entid[0], sub_prop_entid[1], arg1, arg2,), engine)
num_records = len(pd.DataFrame(data).index)
df = pd.DataFrame(data)
if num_records > 0:
count += 1
print( "# Of Records............: " ,num_records , '\n')
df.insert(0,'# Of Records',num_records)
df.insert(1,'Exec Time',tot)
display(df)
print ("Records with good data", count)
你应该理解两者之间的区别。多处理和多线程。我相信后者是完成任务的正确方式 python中的多处理允许您在多个“CPU”中并行运行任务,这意味着任何变量、数据或连接都不能被pickle(即共享)。将每个进程看作一个全新的python程序,您要做的是在不同的python程序之间共享一个变量 所以,尝试使用多线程并将计数器设置为全局变量
import multithreading
global counter
for sub_prop_entid in test_propid_entid:
t_sub = multithreading.Thread(target=sql_fetch, args=(sub_prop_entid,))
multi.append(t_sub)
t_sub.start()
for a in multi:
a.join()
请编辑您问题中的代码,使其成为-这意味着任何人都可以将您的代码粘贴到文件中并运行它,而无需添加任何内容,并且可以看到您有问题的行为。请理解,但您的答案不完整。。您是否可以通过更新“def sql_fetch”来完成此操作?如何将计数器全局变量用于该函数并打印该值。这对其他读者也有帮助。