python 退出阻塞线程?

发布于 2024-07-14 05:35:02 字数 246 浏览 6 评论 0原文

在我的代码中,我循环遍历 raw_input() 以查看用户是否已请求退出。 我的应用程序可以在用户退出之前退出,但我的问题是应用程序仍然处于活动状态,直到我输入一个键从阻塞函数 raw_input() 返回。 我可以通过向其发送虚假输入来强制 raw_input() 返回吗? 我可以终止它所在的线程吗? (它拥有的唯一数据是一个名为 wantQuit 的变量)。

In my code I loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until I enter a key to return from the blocking function raw_input(). Can I do to force raw_input() to return by maybe sending it a fake input? Could I terminate the thread that it's on? (the only data it has is a single variable called wantQuit).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

野鹿林 2024-07-21 05:35:02

为什么不将线程标记为守护进程呢?

来自 文档

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

Why don't you just mark the thread as daemonic?

From the docs:

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon attribute.

執念 2024-07-21 05:35:02

您可以使用这个超时函数来包装您的函数。 以下是食谱:http://code.activestate.com/recipes/473878/

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

You can use this time out function that wraps your function. Here's the recipe from: http://code.activestate.com/recipes/473878/

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
心的憧憬 2024-07-21 05:35:02

您可以使用非阻塞函数来读取用户输入。
这个解决方案是 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 用户论坛的链接):

import sys
import select

i = 0
while i < 10:
    i = i + 1
    r,w,x = select.select([sys.stdin.fileno()],[],[],2)
    if len(r) != 0:
        print sys.stdin.readline()

另请参阅:< a href="http://code.activestate.com/recipes/134892/" rel="nofollow noreferrer">http://code.activestate.com/recipes/134892/

You might use a non-blocking function to read user input.
This solution is windows-specific:

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)

To do something similar in Unix, which reads a line at a time, unlike the windows version reading char by char (thanks to Aaron Digulla for providing the link to the python user forum):

import sys
import select

i = 0
while i < 10:
    i = i + 1
    r,w,x = select.select([sys.stdin.fileno()],[],[],2)
    if len(r) != 0:
        print sys.stdin.readline()

See also: http://code.activestate.com/recipes/134892/

旧时浪漫 2024-07-21 05:35:02

Python 邮件上有一个 帖子list 解释了如何在 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

There is a post on the Python mailing list which explains how to do this for 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文