关于这些与以下代码相关的数据,
12 41 58 82000
12 41 58 190000
12 41 58 301000
12 41 58 416000
12 41 58 524000
12 41 58 632000
12 41 58 741000
12 41 58 849000
12 41 58 959000
12 41 59 65000
12 41 59 174000
12 41 59 281000
12 41 59 389000
12 41 59 496000
12 41 59 605000
12 41 59 711000
12 41 59 820000
12 41 59 927000
12 42 0 36000
12 42 0 143000
12 42 0 252000
12 42 0 360000
12 42 0 469000
12 42 0 577000
12 42 0 685000
12 42 0 793000
12 42 0 901000
12 42 1 9000
代码如下:
from datetime import datetime
minute = 0
second = 0
microsecond=0
fob=open('test_file_thread.txt','w')
def st():
global hour
global minute
exacttime = datetime.now()
hour = exacttime.hour
minute = exacttime.minute
def nd():
global second
global microsecond
exacttime = datetime.now()
second = exacttime.second
microsecond = exacttime.microsecond
while True:
st()
nd()
fob.write(str(hour) + ' '
+ str(minute) + ' '
+ str(second) + ' '
+ str(microsecond) + '\n')
time.sleep(0.1)
现在我想对线程做同样的事情。我使用两个线程从两个串行端口获取数据。由于线程是并行工作的,我不能做一个文本文件来排列row.That的数据行,我想从第一个串口获取数据,将其写入到文本文件的row=0和column=0中,然后从第二个串口读取数据并将其写入row=0和column=5(因此它正好位于来自第一个端口的数据的前面),然后转到下一行(row=1)并重复此过程。我想有一些像“时间的例子”,我做了上面的读取从串口。这是我的代码,我不知道如何修复它,也不知道将命令fob.write(str(x)+' ' +str(y)+'\n')
放在哪里,以便在同一时间将所有内容写入相同的文件。感谢您的帮助
import time, threading
import threading
import serial
x=0
y=0
fob=open('test_file_thread.txt','w')
ser1 = serial.Serial("COM5", baudrate=9600, timeout=1)
ser2 = serial.Serial("COM4", baudrate=9600, timeout=0.25)
def st():
global x
while True:
x = ser1.readline()
def nd():
global y
while True:
y= ser2.readline()
threading.Timer(0, st).start()
threading.Timer(0, nd).start()
fob.write(str(x)+' ' +str(y)+'\n')
发布于 2016-12-11 05:41:59
你应该使用一个队列,实际上是两个队列!
from Queue import Queue
...
ST_Q = Queue()
MD_Q = Queue()
def st():
ST_Q.put(ser1.readline())
def md():
MD_Q.put(ser2.readline())
threading.Timer(0, st).start()
threading.Timer(0, nd).start()
#while loop here?
fob.write(str(ST_Q.get())+' ' +str(MD_Q.get())+'\n')
发布于 2016-12-11 08:11:34
谢谢你,Yoav Glazner,实际上我找到了一个新的方法,我想这也是一个很好的解决方案。我想专门写一个新的帖子。这对我很管用。你认为如何?
import time, threading
import threading
from datetime import datetime
hour=0
minute = 0
second = 0
microsecond=0
fob=open('test_file_thread.txt','w')
def st():
global hour
global minute
while True:
exacttime = datetime.now()
hour = exacttime.hour
minute = exacttime.minute
def nd():
global second
global microsecond
while True:
exacttime = datetime.now()
second = exacttime.second
microsecond = exacttime.microsecond
def hd():
while True:
fob.write(str(hour) + ' '+ str(minute) + ' '+ str(second) + ' '+ str(microsecond) + '\n')
threading.Timer(0, st).start()
threading.Timer(0, nd).start()
threading.Timer(0, hd).start()
https://stackoverflow.com/questions/41075378
复制相似问题