Python:在无限循环内导入变量

时间:2010-12-29 16:30:57

标签: python loops import serial-port infinite-loop

我有两个模块,主机和扫描仪。两者都无限循环地与串行端口通信。我想将变量“bestchannel”从扫描仪导入到主机中,但是通过导入它,扫描仪内的while循环首先运行并永远循环。我希望每个模块分别运行,但能够实时发送彼此的数据。这可能吗?

(扫描ram之外)

示例代码:

Host Loop----------------------------------------------
while True:
    ser.write( assemble("20","FF","FF","64","B") )
    sData = ser.read(100)
    if len(sData)>0:
        for i in range(0, len(sData)-17):
            if sData[i]==chr(1) and sData[i+1]==chr(20) and sData[i+2]==chr(int("A1", 16)):
                height = (ord(sData[i+16])*256+ord(sData[i+17]))/100
                print "Sensor ", ord(sData[i+12]), " is returning height ",
                height, "mm. The minnoisechan:",minchannel

Scanner Loop----------------------------------------------
while True:
    ser.write( scan("FF", "FF", str(scanlength)) )  #Channel Mask, Length
    time.sleep(scanlength+2.0)
    sData = ser.read(100)
    if len(sData)>0:
        for i in range(0, len(sData)-16):
            if sData[i]==chr(1) and sData[i+1]==chr(23) and sData[i+2]==chr(int("C5", 16)):
                for j in range(0, 16):
                    chan[j] = sData[i+5+j]
                    print "channel: ",j+11,"=",ord(chan[j])
                    if ord(chan[j])<minvalue:
                        minvalue=ord(chan[j])
                        minchannel=j+11
                count+=1
                print "count",count,"minvalue:",minvalue,"minchannel:",minchannel
                minvalue=999

我希望扫描仪的minchannel可供主机访问。

示例代码在链接中或在答案中向下,抱歉我必须使用其他浏览器。

1 个答案:

答案 0 :(得分:1)

再说一次,如果你还没有探索过使用线程来实现你的代码,那么我建议让两个循环同时运行。所以像这样:

import threading
import Queue

def host(dataQueue):
    """
    Host code goes here.
    """
    # Check dataQueue for incoming data among other things...
    ....

def scanner(dataQueue):
    """
    Scanner code goes.
    """
    # Put data into dataQueue among other things...
    ....

if __name__ == 'main':
    dataQ = Queue.queue()
    hostThread = threading.Thread(target=host, name="Host", arg=(dataQ,))
    scannerThread = threading.Thread(target=scanner, name="Scanner", arg=(dataQ,))
    hostThread.start()
    scannerThread.start()

至少,这将使您开始一起运行两个进程。您仍然需要弄清楚这一点的线程管理方面。