views:

224

answers:

2

I want my app to loop in python but have a way to quit. Is there a way to get input from the console, scan it for letter q and quick when my app is ready to quit? in C i would just create a pthread that waits for cin, scans, locks a global quit var, change, unlock and exit the thread allowing my app to quit when its done dumping a file or w/e it is doing. DO i do this the same way in python and will it be cross platform? (i see a global single instance in python that was windows specific)

+1  A: 

use the threading module to make a thread class.

import threading;

class foo(threading.Thread):
    def __init__(self):
        #initialize anything
    def run(self):
        while True:
            str = raw_input("input something");

class bar:
    def __init__(self)
        self.thread = foo(); #initialize the thread (foo) class and store
        self.thread.start(); #this command will start the loop in the new thread (the run method)
        if(quit):
            #quit
Samuel
+1  A: 

Creating a new thread is easy enough – the threading module will help you out. You may want to make it daemonic (if you have other ways of exiting your program). I think you can change a variable without locking, too – python implements its own threads, and I'm fairly sure something like self.running = False will be atomic.

The simplest way to kick off a new thread is with threading.Thread(target=):

# inside your class definition
def signal_done(self):
    self.done = True

def watcher(self):
    while True:
        if q_typed_in_console():
            self.signal_done()
            return

def start_watcher(self):
    t = threading.Thread(target=self.watcher)
    t.setDaemon(True)    # Optional; means thread will exit when main thread does
    t.start()

def main(self):
    while not self.done:
        # etc.

If you want your thread to be smarter, have its own state, etc. you can subclass threading.Thread yourself. The docs have more.

[related to this: the python executable itself is single-threaded, even if you have multiple python threads]

John Fouhy