python,有趣的业务与线程和IDE?

时间:2009-02-11 15:02:29

标签: python multithreading ide

也许我不能做我想要的?我希望有一个线程做它想要的和第二个线程来recv用户输入来设置退出标志。使用此代码我想随时输入q退出或打印6次后暂停

import sys
import threading
import time

class MyThread ( threading.Thread ):
    def run (s):
        try:
            s.wantQuit = 0
            while(not s.wantQuit):
                print "want input"
                button = raw_input()
                if button == "q":
                    s.wantQuit=1
        except KeyboardInterrupt:
            s.wantQuit = 1
            print "abort with KeyboardInterrupt"
        print "done mythread"

myThread = MyThread ()
myThread.start()

a=5
while not myThread.wantQuit:
    print "hey"
    if (a == 0):
        break;
    a = a-1;
    time.sleep(1)
myThread.wantQuit=1
print "main thread done"
发生了什么,而不是两个线程,我主要打印嘿4/6次,然后弹出一个对话框询问我的输入和应用程序被锁定,直到我输入它。 WTF?

want input
hey
hey
hey
hey
abort with KeyboardInterrupt
done mythread
main thread done

我正在使用PyScripter(它有调试),我也尝试了pydle,它似乎不允许我输入输入并在运行一次后最终锁定。

1 个答案:

答案 0 :(得分:2)

这里的问题是raw_input等待一个enter来刷新输入流;看看它的documentation。 PyScripter可能看到程序正在等待输入并给你一个输入框(不确定,从未使用它。)

该程序完全按照我的预期从命令行运行; raw_input上的辅助线程阻塞,直到我点击“q [enter]”,此时程序结束。

在AFAICS阻止读取调用之前,很容易检查并查看输入流中是否有可用的字符。你可能应该查看this thread如何以阻塞的方式阅读一个角色而不需要[回车],然后this post查看一个没有阻塞的角色挑战。

您可以在Windows上使用msvcrt.kbhit和在python FAQ中使用this recipe来获取q字符而无需按键,但我会将其作为练习留给读者。

附录:你可以做的一件事就是使用select库来设置键盘读取超时,这将使你的程序更像你期望的行为:

import sys
import threading
import time
import select

def timeout_read(n_chars):
  r, _, _ = select.select([sys.stdin], [], [], 1)
  return r[0].read(n_chars) if r else ""

class MyThread (threading.Thread):
    def run (self):
        try:
            self.wantQuit = 0
            while not self.wantQuit:
                print "want input"
                button = timeout_read(1)
                if button == "q":
                    self.wantQuit=1
        except KeyboardInterrupt:
            self.wantQuit = 1
            print "abort with KeyboardInterrupt"
        print "done mythread"

myThread = MyThread ()
myThread.start()

a=5
while not myThread.wantQuit:
    print "hey"
    if (a == 0):
        break;
    a = a-1;
    time.sleep(1)
myThread.wantQuit=1
print "main thread done"

请注意,您仍需要使用此解决方案按“q [enter]”。

相关问题