python,线程和ide的有趣业务?

2024-09-22 16:42:16 发布

您现在位置:Python中文网/ 问答频道 /正文

也许我不能做我想做的事?我想有一个线程做它想要的和第二个线程接收用户输入设置退出标志。使用这段代码,我想随时输入q退出或在打印hey 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次,然后弹出一个对话框,要求我的输入和应用程序被锁定,直到我进入。世界跆拳道联盟?!在

^{pr2}$

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


Tags: importinputiftimenotbutton线程print
1条回答
网友
1楼 · 发布于 2024-09-22 16:42:16

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

程序的工作方式与我在命令行中期望的完全一样;次线程阻塞原始输入,直到我点击“q[enter]”,此时程序结束。在

实际上,在阻塞读调用之前,检查和查看输入流中是否有字符是不容易的。您可能应该看看this thread如何在不需要[enter]的情况下以阻塞的方式读取字符,然后this post学习如何在完全不阻塞的情况下读取字符。在

你可以使用msvcrt.kbhit在windows和python常见问题解答中的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]”。在

相关问题 更多 >