[英]How can I break out of a real-time while loop gathering data without using the keyboard or keyboard interrupt?
因此,我使用 National Instruments 數據采集系統持續測量溫度數據,我已經能夠 plot 實時溫度測量值並將其存儲到 dataframe 中,然后我可以保存。
我要做的是將“采樣率”范圍設置為非常高的值(現在為 301),然后在我不再想獲取溫度數據時停止它。 有時我只需要收集 100 個樣本,有時超過 10k。
當我使用此代碼中斷循環時,它會在控制台中打印我所要求的內容,但實際上我無法在控制台中輸入任何內容。 控制台對鍵盤中斷完全沒有響應。
無論如何,我可以在不使用鍵盤的情況下提前跳出這個循環嗎?
import nidaqmx
import matplotlib.pyplot as plt
import pandas as pd
plt.ion()
Samples = []
time = []
freezerTemp = []
rightSideTemp = []
def print_menu():
print('Press "3" and hit "Enter" to exit ')
print('3. Exit')
with nidaqmx.Task() as task:
FreezerT = task.ai_channels.add_ai_thrmcpl_chan("cDAQ1Mod1/ai0")
RightSideT = task.ai_channels.add_ai_thrmcpl_chan("cDAQ1Mod1/ai3")
#This controls the sample/second. i.e. if 2 then 2 samples/second.
samplerate = task.timing.samp_clk_rate = 1
while True:
print_menu()
for samplerate in range(301):
data = task.read()
Samples.append(samplerate)
freezerTemp.append(data[0])
rightSideTemp.append(data[1])
time.append(samplerate/1)
plt.xlabel('Samples')
plt.ylabel('Temperature (C)')
plt.scatter(samplerate,freezerTemp[samplerate],c='r')
plt.scatter(samplerate,rightSideTemp[samplerate],c='b')
plt.pause(0.05)
plt.show()
choice = input('Enter a number: ')
if choice == '3':
break
df = pd.DataFrame({'Samples': Samples,
'Time(sec)': time,
'Freezer Temperature': freezerTemp,
'Right Side': rightSideTemp})
print(df)
你的問題是plt.show()
。 這本身就是一個循環,它會阻塞代碼的 rest。
但是 matplotlib 具有在plt.show()
之后捕獲關鍵命令的功能。 在這里看看他們的演示。
https://matplotlib.org/3.1.0/gallery/event_handling/keypress_demo.html
您需要在不同的(后台)線程中運行采樣和繪圖,以便您的主線程保持響應。
查看線程模塊https://docs.python.org/3/library/threading.html
戰略:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.