0

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

4

2 回答 2

1

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

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
于 2009-02-09T02:47:34.260 回答
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 线程]

于 2009-02-09T03:43:15.980 回答