python控制台插入?和跨平台线程
我希望我的应用程序在python中循环,但有办法退出。当我的应用程序准备退出时,有没有办法从控制台获取输入、扫描字母q并快速执行?在C语言中,我只需要创建一个pthread,它等待cin、扫描、锁定一个全局退出变量、更改、解锁并退出线程,允许我的应用程序在转储文件或执行w/e时退出。我在python中也是这样做的吗?它会是跨平台的吗?(我在python中看到一个特定于windows的全局单实例)使用线程模块创建线程类python控制台插入?和跨平台线程,python,multithreading,console,quit,Python,Multithreading,Console,Quit,我希望我的应用程序在python中循环,但有办法退出。当我的应用程序准备退出时,有没有办法从控制台获取输入、扫描字母q并快速执行?在C语言中,我只需要创建一个pthread,它等待cin、扫描、锁定一个全局退出变量、更改、解锁并退出线程,允许我的应用程序在转储文件或执行w/e时退出。我在python中也是这样做的吗?它会是跨平台的吗?(我在python中看到一个特定于windows的全局单实例)使用线程模块创建线程类 import threading; class foo(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
创建一个新线程非常简单–线程模块将帮助您解决这个问题。您可能希望将其设为daemonic(如果您有其他退出程序的方法)。我认为您也可以在不锁定的情况下更改变量–python实现了自己的线程,而且我相当确定类似
self.running=False
的东西将是原子的
启动新线程的最简单方法是使用线程。线程(target=)
:
如果你想让你的线程更智能,就要有自己的状态,等等。你可以自己给threading.thread子类。这些文件还有更多
[与此相关:python可执行文件本身是单线程的,即使您有多个python线程]
# 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.