我對 Python 中的 time.sleep() 管理有一些問題。我想在腳本的第二部分中使用一些值,但它們必須相互延遲 300 毫秒,我只想延遲腳本的那部分而不是所有其余部分。這些值是相機檢測到的物件的 X 坐標。腳本是這樣的:
while True:
if condition is True:
print(xvalues)
time.sleep(0.3)
if another_condition is True:
#do other stuff and:
np.savetxt('Xvalues.txt', xvalues)
在腳本的第二部分(#do other stuff)中,我將撰寫檢測到 X 坐標的 G 代碼行,并將它們發送到 CNC 機器。如果我在腳本的那個位置寫一個 time.sleep(),while 回圈中的所有內容都會被延遲。
如何在不影響腳本其余部分的情況下提取一些每次 300 毫秒采樣的值?
uj5u.com熱心網友回復:
from threading import Thread
class sleeper(Thread):
if condition is True:
print(xvalues)
time.sleep(0.3)
class worker(Thread):
if another_condition is True:
#do other stuff and:
np.savetxt('Xvalues.txt', xvalues)
def run():
sleeper().start()
worker().start()
uj5u.com熱心網友回復:
您可以將 300ms 檢查作為處理的一部分condition。
第一次檢測condition,獲取并記住變數中的當前時間。
下一次condition再次為真,檢查它是否與上次condition為真的時間相差 300 毫秒以上。
像這樣的東西:
last_condition_time=None
while True:
if condition is True:
if not last_condition_time or more_than_300ms_ago(last_condition_time):
print(xvalues)
last_condition_time = get_current_time()
if another_condition is True:
#do other stuff and:
np.savetxt('Xvalues.txt', xvalues)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/321313.html
上一篇:使用openCV檢測墻角-困難
