如何安全地停止无限循环以完成在 Python 中收集 Json 数据?

How to safely stop an infinite loop to finish gathering Json data in Python?

我有一个脚本,它在无限循环上运行,从 Arduino 收集数据并将此信息添加到 json 文件中。当我用 cnt c 停止程序时,它切断了 while 循环,因此没有正确地完成将数据发送到 json 文件。

我查看了其他堆栈溢出问题。就像我曾经在我的代码中实现的这个 但它有时只会正确终止 json 数据。

我的 while 循环看起来像这样:

interrupted = False

while True:
    serialDataDic= ArduinoSerial(arduinoSerial,68,startTimeofData)# gather x amount of samples of data at 8.9kHz
    # print(serialDataDic)
    

    
    decompositionCoeffiecients=DWT(serialDataDic['voltage'],'haar',2)
    # print(decompositionCoeffiecients)
   
   #looping through each of our functions and placing that info in our dictionary to go to our json file  
    for key in serialDataDic:
        plottingDicData[key].append(serialDataDic[key])
    for key in decompositionCoeffiecients:
        plottingDicData[key].append(decompositionCoeffiecients[key])
    # print(plottingDicData)
    #sending out sensor data into a json file 
    jsonfileData=JsonData(fileName,plottingDicData)
    
    if interrupted:
        print("Gotta go")
        break

如何正确终止此 while 循环,使其在终止前完成 json 数据收集?

我认为您可能需要某种形式的 try 循环与一条 except 行结合使用,该行明确捕获键盘中断,然后使用 sys.exit() 方法在最后强制退出(以及发送您在括号中包含的消息)。

这样,您的脚本将 运行 通常在 try 循环下,然后 KeyboardInterrupt 将捕获您的 ctrl-C 但将其强制为您想要的 w/e,然后强制退出。

这当然可以稍微清理一下,但希望这是清楚的。

import sys

while True:
    try:
        serialDataDic= ArduinoSerial(arduinoSerial,68,startTimeofData)# gather x amount of samples of data at 8.9kHz
        # print(serialDataDic)
        decompositionCoeffiecients=DWT(serialDataDic['voltage'],'haar',2)
        # print(decompositionCoeffiecients)
   
        #looping through each of our functions and placing that info in our dictionary to go to our json file  
        for key in serialDataDic:
            plottingDicData[key].append(serialDataDic[key])
        for key in decompositionCoeffiecients:
            plottingDicData[key].append(decompositionCoeffiecients[key])
        # print(plottingDicData)
        #sending out sensor data into a json file 
        jsonfileData=JsonData(fileName,plottingDicData)
    
    except KeyboardInterrupt:
        decompositionCoeffiecients=DWT(serialDataDic['voltage'],'haar',2)
        # print(decompositionCoeffiecients)
   
        #looping through each of our functions and placing that info in our dictionary to go to our json file  
        for key in serialDataDic:
            plottingDicData[key].append(serialDataDic[key])
        for key in decompositionCoeffiecients:
            plottingDicData[key].append(decompositionCoeffiecients[key])
        # print(plottingDicData)
        #sending out sensor data into a json file 
        jsonfileData=JsonData(fileName,plottingDicData)
        # The below line force quits and prints the included string
        sys.exit("User manually terminated script with ctrl-C")