Question

I can't see why I get a indentation error at the first "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()

What I am trying to do is that I want to store a value in the storingThread while listeningThread constantly listens for new input to replace the currently stored.

But since I am new to Python I have been wrestling with this error for quite a while now and though I might as well ask you helpful people :)

Was it helpful?

Solution

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?

I'm confused though -- aren't your Listen (and presumably Store) objects supposed to be threads? Why are you building a class, instantiating an object, then running a thread that accesses one of that object's methods? Just build a thread object!

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

OTHER TIPS

In addition to indenting print "Choose a direction", you'll also want to indent the stuff under "while 1==1:" so that python knows what code is inside your while loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top