如何每15秒执行循环并在同一图表中更新数据分析结果?
Hey there! Let's break down the two core issues in your code and fix them step by step:
1. New File Filtering Logic Issues
- First off, your
Save_datafunction referencesT_startandT_stepvariables that are defined in the main loop—this will throw aNameError(which your currentValueErrorcatch won't handle). - More importantly, the file filtering logic is flawed: using
T_start - T_stepmeans you might reprocess the same files in every loop. Instead, you need to track the last time you finished processing files and only handle files modified after that timestamp.
Here's the fixed Save_data function:
def Save_data(path, last_processed_time): my_data = {} for filename in os.listdir(path): file_path = os.path.join(path, filename) file_mtime = os.path.getmtime(file_path) # Only process files modified after the last check if file_mtime > last_processed_time: try: data = np.genfromtxt(file_path, skip_header=skip_head) my_data[filename] = data[:, [0, 1]] except IndexError: # Skip broken files instead of returning early continue return my_data
2. Chart Auto-Update Issues
plt.show()blocks your program until you close the chart window, which stops the loop entirely.- You're reusing
plt.figure(1)but never clearing old plot content, so new data will just overlap with the old (even if the window wasn't blocked).
Fix the plotting function with matplotlib's interactive mode:
import matplotlib.pyplot as plt # Enable interactive mode for real-time updates plt.ion() def PlotAverage(aver_voltage, std_dev, title, x): plt.figure(1) # Clear existing plot content before drawing new data plt.clf() plt.errorbar(x, aver_voltage, yerr=std_dev, fmt='r', ecolor='gray', label=title) plt.title(title) plt.xlabel('Time [mus]') plt.ylabel('Voltage [V]') plt.legend() # Refresh the chart without blocking plt.draw() plt.pause(0.001) # Give a tiny buffer for rendering
Fixed Main Loop
Update the main loop to track the last processed time and handle edge cases properly:
import time import numpy as np import os # Initialize timestamp to catch all existing files on first run last_processed_time = time.time() T_step = 15 while True: try: current_time = time.time() # Fetch only files added/modified since last loop my_data = Save_data(path, last_processed_time) if not my_data: print("\nNo new files in the folder since last check.") last_processed_time = current_time time.sleep(T_step) continue # Run your analysis pipeline tot_voltage, aver_voltage = Average_signal(my_data) std_dev = np.std(tot_voltage, axis=1) x = TimeVector(my_data, tot_voltage) # Update the chart PlotAverage(aver_voltage, std_dev, title, x) # Update timestamp to avoid reprocessing files last_processed_time = current_time # Adjust sleep time to account for processing duration (optional) elapsed = time.time() - current_time time.sleep(max(0, T_step - elapsed)) except ValueError as e: print(f"\nValue error occurred: {e}") time.sleep(T_step) continue except Exception as e: # Catch unexpected errors to prevent crash print(f"\nUnexpected error: {e}") time.sleep(T_step) continue
Quick Notes:
- Make sure
skip_head,path, andtitleare properly defined in your code. - Double-check that
Average_signalandTimeVectorwork with themy_datastructure returned by the updatedSave_data.
内容的提问来源于stack exchange,提问作者summerfield
相关产品推荐
相关产品推荐

