为什么会出现缩进错误



我不明白为什么在第一个"def run"处出现缩进错误

import threading, time, sys 
class Listen:
     def __init__(self): 
        print "Choose a direction. Forwards (1) or Backwards (2) or to quit type 'quit'"        
        direction = 0 
     def run (threadName): 
        while 1==1 : 
        print "%s Listening for direction: " %(threadName) 
        direction = input 
        time.sleep(1) 
        if (direction != 1 or 2):
           print "You entered a incorrect value" 
        elif (direction=='quit'): 
           break 
           thread.exit() 
        else:
           return direction 
class Store:
     def run (threadName, direction):
       print "%s %s" %(threadName, direction)
if __name__ == '__main__':
     l = Listen()
     s = Store()
     listeningThread = threading.Thread(target=l.run, args=()) 
     storingThread = threading.Thread(target=s.run, args=())            
     listeningThread.start() 
     storingThread.start()

我想做的是,我想在storingThread中存储一个值,而listeningThread不断地侦听新的输入来替换当前存储的。

但是因为我是Python的新手,我已经和这个错误搏斗了很长一段时间了,尽管我可能会问你有帮助的人:)

def __init__(self):
print "Choose a direction. Forwards (1) or Backwards (2) or to quit type 'quit'"
^ indented line here? Maybe the WHOLE THING should be indented?

我很困惑——你的Listen(大概是Store)对象应该是线程吗?为什么要构建一个类,实例化一个对象,然后运行一个线程来访问该对象的方法之一?只需构建一个线程对象!

class Listen(threading.Thread):
    def __init__(self):
        self.direction = 0
        super().__init__() # runs the superclass's (Thread's) __init__ too
    def run(self):
        while True: # 1==1? Just use True and remove a compare op each iteration
            print "%s listening for input" % self
            self.direction = input # this is currently a NameError -- what's input?
            time.sleep(1)
            if self.direction not in (1,2):             # direction != 1 or 2
                print "You entered an incorrect value"  # doesn't do what you think
            elif self.direction == 'quit':              # it does. It does:
                break                                   # if direction != 1 OR if 2
            else:
                return direction # this will exit the loop! use a queue.Queue if
                                 # you need to pass messages from a thread.
l = Listen() # don't name variables l. It looks like 1.
l.start()

除了缩进打印"选择一个方向",您还需要缩进"while 1==1:"下面的内容,以便python知道while循环中的代码。

相关内容

  • 没有找到相关文章

最新更新