如何将来自Python中多个线程的同时数据写入csv文件

2024-04-26 02:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我从线程1获取鼠标坐标(鼠标x,鼠标y),线程1与tkinter一起工作。 我有另一个线程(线程2)同时工作,用opencv同时获得凝视方向估计(凝视x,凝视y)

现在我想把它们同时写在同一个csvfile上,如果有数据是空的就不写。你知道吗

我可以从每个线程获得一个tmp文件来写入csv文件,但不能同时这样做

with open(csv_filename, 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, dialect=csv.excel, delimiter=',',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["mouse_x","mouse_y","gaze_x","gaze_y"])

def get_mouse_coordinates():
        def motion(event):
                  x, y = event.x, event.y
                  tmp = [x, y]
                  with open(csv_filename, 'a+', newline='') as csvfile:
                          writer = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL) 
                           writer.writerow(list(tmp))
t1 = Thread(target=get_mouse_coordinates)
t1.start()


def get_gaze_coordinates
   .....
    gaze_x,gaze_y = ....

t2 = Thread(target=get_gaze_coordinates)
t2.start()

我试图写分开的冒号,但csv文件不能同时填写。。。。 我会感激任何帮助。。。 致以最诚挚的问候

编辑:我需要同时记录两个数据。在这里,我需要记录目标的精确位置(这里是鼠标指针)以及目标的注视方向,我需要在给定的精确时刻将它们写在同一行上,这样我就可以关联。是吗没有一个同时采样两列数据进行关联?你知道吗


Tags: 文件csv数据csvfileeventgetdef鼠标
1条回答
网友
1楼 · 发布于 2024-04-26 02:24:16

为了将多个线程中的数据同时写入单个文件,应该创建一个同步机制。例如-另一个线程:

queuForSync1 = queue.Queue(1)
queuForSync2 = queue.Queue(1)
t1 = Thread(target=get_mouse_coordinates, args=(queuForSync1,))
# in get_mouse_coordinates you have to: queuForSync1.put(dataFromThread1)
t1.start()
...
t2 = Thread(target=get_gaze_coordinates, args=(queuForSync2,))
# in get_gaze_coordinates you have to: queuForSync2.put(dataFromThread2)
t2.start()
...
tSync = Thread(target=syncThread, args=(queuForSync1, queuForSync2, fileName))
tSync.start()
...
def syncThread(q1, q2, fileName):
    dataFromThread1 = None 
    dataFromThread2 = None 
    with open(fileName, 'a+', newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) 
        while True:  # Here - a sync Event May be used to get out of the Loop and Join Thread Nicely
            try:
                dataFromThread1 = q1.get(block=False)
            except Exception as ex:
                pass
            # ... same for dataFromThread2
            if dataFromThread1 is not None and dataFromThread2 is not None :
                writer.writerow(list(dataFromThread1, dataFromThread2))  # Here data will be written Into File.
                csvfile.flush()  # Important

另外,如果来自1个线程的数据没有改变,而来自2个线程的数据不断改变,那么可以创建一个缓冲区来存储从线程接收的最后一个数据。你知道吗

相关问题 更多 >