我正在从多个设备收集数据,并且由于测试持续时间很长,我想使用 Pythonthreading
和Queue
模块。我写了一个简短的脚本来弄清楚如何使用这些,很明显我不明白让它工作的细微差别。
这是我的脚本:
import ue9
import LJ_Util
import DAQ_Util
import threading
import Queue
from datetime import datetime
from time import sleep
queue = Queue.Queue()
now = datetime.now().isoformat()
def DAQThread(ue9ipAddr):
print '\nExecuting in DAQThread at IP Address: %s' % ue9ipAddr
a = ue9.UE9(ethernet=True, ipAddress=ue9ipAddr)
SN = (a.commConfig()).get('SerialNumber')
count = 5
while count > 0:
reading = a.feedback()
dataReturn = (SN, now, reading)
queue.put(dataReturn)
count -= 1
print count
sleep(5)
def listenThread(counter):
while queue.empty() != True:
try:
outcome = queue.get()
print outcome
counter -=1
print counter
except:
return 'queue.get() command loop failing.'
print "\nOpening device..."
ipAdd = '192.168.1.127'
feedbackThread = threading.Thread(target=DAQThread, args=(ipAdd,))
feedbackThread.start()
print "\nListening for data..."
queryThread = threading.Thread(target=listenThread, args = (10,))
queryThread.start()
print queue.get()
print(threading.activeCount())
print "\nDone"
这是执行此脚本的输出结果:
$ python threading-and-queue-test.py
Opening device...
Executing in DAQThread at IP Address: 192.168.1.127
Listening for data...
4
(278956853, '2012-09-03T20:02:47.656024', {'AIN4': -0.012, 'AIN5': -0.012, 'CIODir': 0, 'AIN7': -0.012, 'EIODir': 0, 'AIN1': -0.012, 'AIN2': -0.012, 'AIN3': -0.012, 'MIOState': 7, 'AIN8': -0.012, 'AIN6': -0.012, 'AIN9': -0.012, 'CIOState': 15, 'AIN0': -0.012, 'Counter0': 0, 'Counter1': 0, 'EIOState': 255, 'TimerC': 0, 'TimerB': 0, 'TimerA': 0, 'MIODir': 0, 'FIODir': 32, 'AIN14': -0.012, 'AIN15': -0.012, 'AIN12': -0.012, 'AIN13': -0.012, 'AIN10': -0.012, 'AIN11': -0.012, 'FIOState': 255})
2
Done
3
2
1
0
$
很明显线程活动的时间是“关闭”的,但我不确定如何修复它,因为我以前从未使用这些模块进行编程,也没有使用过一般的线程。欢迎任何意见或建议。提前致谢!