python控制台中断?和跨平台线程

时间:2009-02-09 02:07:22

标签: python multithreading console quit

我希望我的应用程序在python中循环,但有办法退出。有没有办法从控制台获取输入,扫描字母q并在我的应用程序准备好退出时快速扫描?在C我只会创建一个等待cin,扫描,锁定全局退出var,更改,解锁和退出线程的pthread,允许我的应用程序在完成转储文件或w / e正在执行时退出。我是否在python中以相同的方式执行此操作并且它是跨平台的吗? (我在python中看到一个特定于Windows的全局单个实例)

2 个答案:

答案 0 :(得分:1)

使用线程模块创建一个线程类。

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

答案 1 :(得分:1)

创建新线程非常简单 - 线程模块可以帮助您。您可能希望使其成为守护进程(如果您有其他退出程序的方法)。我认为你也可以在没有锁定的情况下改变变量 - python实现了自己的线程,我很确定像self.running = False这样的东西是原子的。

启动新主题的最简单方法是使用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.

如果您希望您的线程更智能,拥有自己的状态等,您可以自己继承threading.Thread。文档有更多。

[与此相关:python可执行文件本身是单线程的,即使你有多个python线程]