Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python是否退出阻塞线程?_Python_Multithreading_Raw Input - Fatal编程技术网

python是否退出阻塞线程?

python是否退出阻塞线程?,python,multithreading,raw-input,Python,Multithreading,Raw Input,在我的代码中,我通过raw\u input()循环查看用户是否请求退出。我的应用程序可以在用户退出之前退出,但我的问题是,在我输入一个键从阻止函数raw\u input()返回之前,该应用程序仍然处于活动状态。我可以通过发送一个假输入来强制raw\u input()返回吗?我可以终止它所在的线程吗?(它只有一个名为wantQuit)的变量。您可以使用非阻塞功能读取用户输入。 此解决方案特定于windows: import msvcrt import time while True: #

在我的代码中,我通过
raw\u input()
循环查看用户是否请求退出。我的应用程序可以在用户退出之前退出,但我的问题是,在我输入一个键从阻止函数
raw\u input()
返回之前,该应用程序仍然处于活动状态。我可以通过发送一个假输入来强制
raw\u input()
返回吗?我可以终止它所在的线程吗?(它只有一个名为
wantQuit
)的变量。

您可以使用非阻塞功能读取用户输入。
此解决方案特定于windows:

import msvcrt
import time

while True:
    # test if there are keypresses in the input buffer
    while msvcrt.kbhit(): 
        # read a character
        print msvcrt.getch()
    # no keypresses, sleep for a while...
    time.sleep(1)
要在Unix中执行类似操作,它一次读取一行,不同于windows版本逐字符读取(感谢Aaron Digulla提供python用户论坛的链接):

导入系统 导入选择 i=0 当我<10时: i=i+1 r、 w,x=select.select([sys.stdin.fileno()],[],[],[]2) 如果len(r)!=0: 打印sys.stdin.readline()
另请参见:

您可以使用此超时函数包装您的函数。以下是来自:

下面有一个示例说明了如何在Unix上执行此操作:

# this works on some platforms:

import signal, sys

def alarm_handler(*args):
    raise Exception("timeout")

def function_xyz(prompt, timeout):
    signal.signal(signal.SIGALRM, alarm_handler)
    signal.alarm(timeout)
    sys.stdout.write(prompt)
    sys.stdout.flush()
    try:
        text = sys.stdin.readline()
    except:
        text = ""
    signal.alarm(0)
    return text

为什么不把线程标记为守护线程呢

从:

线程可以标记为“守护线程”。此标志的意义在于,当只剩下守护进程线程时,整个Python程序将退出。初始值从创建线程继承。可以通过daemon属性设置该标志


谢谢,我在我的回答中添加了一个基于那篇文章的小例子(+1)谢谢。修复了链接并在这里复制了源代码。这段代码是个谎言:InterruptableThread实际上是不可中断的。它会挡住任何一条路,永远留在你身边。它至少应该被标记为守护进程线程,这样它就不会阻止解释器退出。有人已经注意到了这个问题:
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
    '''This function will spwan a thread and run the given function using the args, kwargs and 
    return the given default value if the timeout_duration is exceeded 
    ''' 
    import threading
    class InterruptableThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.result = default
        def run(self):
            try:
                self.result = func(*args, **kwargs)
            except:
                self.result = default
    it = InterruptableThread()
    it.start()
    it.join(timeout_duration)
    if it.isAlive():
        return it.result
    else:
        return it.result
# this works on some platforms:

import signal, sys

def alarm_handler(*args):
    raise Exception("timeout")

def function_xyz(prompt, timeout):
    signal.signal(signal.SIGALRM, alarm_handler)
    signal.alarm(timeout)
    sys.stdout.write(prompt)
    sys.stdout.flush()
    try:
        text = sys.stdin.readline()
    except:
        text = ""
    signal.alarm(0)
    return text