我可以让多处理和多线程独立地与谷歌表格APIv4一起工作,但我不能让它们一起工作。
多处理(这有效(:
from multiprocessing import Pool
import threading
import pandas
class B:
def __init__(self):
self.core = 10
self.b()
def b(self):
p = Pool(self.core)
p.map(multicore, range(10))
def multicore(*args):
thread = 0
if thread == 1:
thread_list = []
for i in range(10):
thread = threading.Thread(target=output_function, args=(i,))
thread_list.append(thread)
thread.start()
else:
output_function(*args)
def output_function(*args):
x = args[0]
print(x * x)
g.build_service()
g.export_df(g.test_API_key, ['output!A' + str(x + 1)], [pandas.DataFrame([[x * x]])], 'n')
多线程(这也可以(:
def just_threading():
thread = 1
if thread == 1:
thread_list = []
for i in range(10):
thread = threading.Thread(target=output_function, args=(i,))
thread_list.append(thread)
thread.start()
def output_function(*args):
x = args[0]
print(x * x)
g.build_service()
g.export_df(g.test_API_key, ['output!A' + str(x + 1)], [pandas.DataFrame([[x * x]])], 'n')
但是当我通过为第一个示例设置 thread = 1
来组合它们时,我绝对没有得到谷歌表格的输出(print(x*x)
仍然有效(。
有趣的是,如果我拿走g.build_service()
,它将输出几行,直到遇到此处概述的线程安全问题:错误ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:2273)
https://developers.google.com/api-client-library/python/guide/thread_safety。因此,重建服务确实很重要,但我看不到工作表的输出!
您需要等待线程完成其工作,否则主线程将在完成之前退出。
启动线程后,运行:
for t in thread_list:
t.join()