因此,我已经在python中使用*args **kwargs功能一段时间了,我遇到了一个问题,在文档中/这里,我似乎找不到关于堆栈溢出的解决方案。
我有一个多线程作业,它并行地向服务器发送请求,然后对返回的JSON进行一些分析。我需要为每个请求-响应对写入csv文件一行。
因为这是并行完成的,所以在线程作业函数中写入csv是有问题的。我想出的解决方案是将分析结果放入que中,然后创建一个函数从que的分析中获取它,然后按顺序将其写入csv。
现在到真正的问题:我必须写到csv的函数接受参数和关键字参数,但是que不知道如何处理它。
有没有办法把*args **kwargs放在一个que中,然后一个接一个地将它们传递给另一个函数?
我想要像这样的东西:
csv_que = Queue()
# put arguments to the que which will be written later
def write_row_to_que(self,*args, **kwargs):
csv_que.put(*args, **kwargs)
# send each argument in the que to the write_row function with the arguments
#from the que
def csv_writer_func():
while True:
args, kwargs = csv_que.get()
write_row(args, kwargs)我不知道这是否是解决这个问题的正确方法,但我希望听到一些想法,以及这种功能(将参数传递给que,然后从它中提取它们)是否可能。
发布于 2018-03-01 16:21:09
这一模式应该足以让你开始:
def write_row_to_que(self,*args, **kwargs):
csv_que.put( (args, kwargs) )将参数放入元组中,另一端的get()方法将检索它们。
args, kwargs = csv_que.get()这一行将检索这些项,但是:
args将是未命名参数的元组。kwargs将是最初提供的关键字参数的字典。发布于 2018-03-01 16:15:39
只需将实际对象作为元组传递,而不对它们进行解压缩:
csv_que = Queue()
# put arguments to the que which will be written later
def write_row_to_que(self,*args, **kwargs):
csv_que.put((args, kwargs))
# send each argument in the que to the write_row function with the arguments
#from the que
def csv_writer_func():
while True:
args, kwargs = csv_que.get()
write_row(args, kwargs)https://stackoverflow.com/questions/49053956
复制相似问题