为什么我会出现缩进错误?

时间:2014-03-11 16:29:23

标签: python indentation python-multithreading

我无法理解为什么在第一次" def运行时出现缩进错误"

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()

我想要做的是我想在storedThread中存储一个值,而listenThread会不断地监听新输入以替换当前存储的值。

但是因为我是Python的新手,所以我已经在这个错误中挣扎了很长一段时间,虽然我不妨问你们有帮助的人:)

2 个答案:

答案 0 :(得分:4)

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()

答案 1 :(得分:0)

除了缩进     打印“选择方向”, 你还想在“while 1 == 1:”下缩进这些内容,以便python知道你的while循环中有什么代码。