Python线程是我需要的吗?

2024-04-27 04:07:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个python脚本来控制设置的各个硬件部分。 我有一个状态,我想保持,而其他部分的脚本做他们的事情。 我认为这个while循环会阻止脚本的其他部分运行。 我是否需要引入线程,以便循环可以继续运行,直到我告诉它停止?你知道吗

不确定我是否在寻找正确的方法来解决我的问题。你知道吗

编辑: 我已经粘贴了一些代码,整个事情是相当大的。你知道吗

它侦听usbmidi设备中特定类型的消息,并根据inst中列出的输入值执行操作

while True:
    b = f.read(1)
    s='rawdataB:'+  hex(ord(b))
    print s

    if b == '\x90':
        note=True
    elif note:
        if b in inst:
            print "IsNote:"  + str( int(hex(ord(b)), 16))
            noteaction(inst.get(b))
        note=False

    if b== '\xB0':
        controller=True

    elif controller:
    #grab the controller with byte 1, value with byte 2
        bcount = bcount +1
        cn=hex(ord(b))  #hex value of byte
        if bcount == 1:
            cntrl=cn
            if cntrl== '0xd':
                fspeedC= 1
                print 'fspeed cnum'     

            elif bcount == 2:
                cval=cn 
        if fspeedC == 1:
            fspeed= int(cval,16)
            print 'fspeed=' + str(fspeed)
            MotorControl('fwd',fspeed,0)
            print 'moving forward'
            print "cn:" + str(cntrl) + ", val:" + str(cval)
            print "bcount: " + str(bcount)
            bcount=0
            cvalue=True

    elif cvalue:
        val=int(hex(ord(b)), 16)
        #print "2val:" + str(val)        
        if val != -1 :
            print "do something" 
            cvalue=False
            print "cn:" + str(cntrl) + ", val:" + str(val)
        controller=False

# this will be a function i guess but also can be in an infinite loop mode when I want it to be
# however while this is running I still want the above code to monitor the incoming MIDI bytes
x=0
while True:
    GPIO.wait_for_edge(11, GPIO.FALLING)  
    #prevent bounce
    time.sleep(0.2)
    x=x+1
    print x
    if x % 2 == 0:
         ControlAPairOfPins("17","1","24","0")
         print "Forward"
    else:
         ControlAPairOfPins("17","0","24","1")
         print "backward"

Tags: 脚本trueifvalcnprinthexcontroller
1条回答
网友
1楼 · 发布于 2024-04-27 04:07:36

如果希望在执行其他操作时保持循环运行,可以使用Pythonthreading模块。这方面的例子是

import time
import threading

def loop(n=10):
    while n>0:
        print n
        n -= 1
        time.sleep(1)

t = threading.Thread(target=loop)
print 'hello world'
t.start()

你好,世界 10 9 8 7 6 5 4 三 2 1个

相关问题 更多 >