首页 > 解决方案 > 使用 Python 在新线程中创建 csv 文件

问题描述

我想使用新线程创建一个 csv 文件。下面是我写的代码:

import GPS_lib as GPS
import time
from threading import Thread
import csv

def GPSThread():
    try:
        GPS.gps=GPS.InitConnection()

        last_print_gps=time.time()
        with open(GPS.PATH,"w") as csvfile:
             fieldnames=['Time','Latitude','Longitude','Speed','CoG']
             writer=csv.DictWriter(csvfile,fieldnames=fieldnames)
             writer.writeheader()

             while True:
                  GPS.gps.update()
                  current_gps=time.time()
                  print(GPS.LATITUDE)
                  if current_gps-last_print_gps>=1:
                       last_print_gps=current_gps
                       GPS.GetGPSValues()     
                       writer.writerow({
                      'Time':GPS.TIME,
                      'Latitude':GPS.LATITUDE,
                      'Longitude': GPS.LONGITUDE,
                      'Speed': GPS.SPEED, 
                      'CoG': GPS.CoG})
    except:
         print("Error")


GPS_thread=Thread(target=GPSThread,args=())
GPS_thread.start()
GPS_thread.join()

如果我在没有新线程的情况下使用此代码,则一切正常。使用新线程我只有空文件。为什么?有人能帮我吗?

标签: pythonpython-3.xmultithreading

解决方案


推荐阅读