【问题标题】:Python: Running a thread while taking user's inputPython:在接受用户输入的同时运行线程
【发布时间】:2016-12-06 00:42:36
【问题描述】:

我学习 python 是为了好玩,我在这里想要实现的是一个程序,它通过While True 循环不断要求用户输入,同时仍在后台运行其他脚本(由用户选择)

我目前的工作正常...但不完全符合我的要求。它接受用户的输入并按要求启动线程,但在等待用户的下一个输入时暂停它们。然后,它会在控制台的下一次打印之后打印我的线程应该每秒打印的内容,但只打印一次。

我正在使用 IDLE 定期测试我的代码,也许这会有所帮助。

主要脚本

from mythreadclass import MyThread

while True:
    user_input = input("What do I do ? ")

    if user_input == "start thread":
        #Will start a threat that prints foo every second.
        mythread = MyThread()
        mythread.start()

    elif user_input == "hello":
        print("Hello !")

    else:
        print("This is not a correct command.")

线程类

import time
from threading import Thread, Timer

class MyThread(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        print("Thread started !")
        while True:
            self.foo()
            time.sleep(1)

    def foo(self):
        print("foo !")

执行时我有什么

What do I do ?
>>> start thread
Thread started !
What do I do ?
>>> hello
foo !Hello !
>>> hello
foo !Hello !

如您所见,线程应该每秒打印一次foo!,同时仍然要求用户输入下一个输入。相反,它启动线程并仅在用户键入内容时打印foo !:输入暂停/阻塞线程。

我不知道我想要实现的目标是否明确,所以在这里

What do I do ?
>>> start thread
Thread started !
What do I do ?
foo !
foo !
foo !
#User waited 3 seconds before typing hello so there should be 3 foos
>>> hello
Hello !
What do I do ?
foo !
foo ! 

etc etc.

【问题讨论】:

  • 我将 input 更改为 raw_input,这一切似乎都按预期工作。我把所有东西都放在一个文件里。
  • 您在此处编写的方式在 python 3.5 中非常适合我。这正是您所写的内容还是示例?
  • @JustinBell 这是一个(very) 简化的例子,但我的整个项目是全局相同的(在另一个文件中转换线程的主体类)
  • @sal 我在 Python 3.5 中,raw_input() 已更改为 input() !
  • 好的。但与 JustinBell 一样,这在 python 2.7 中对我有用。

标签: python multithreading python-3.x


【解决方案1】:

你做错了线程。 run() 方法必须是这样的无限循环,而不是无限递归:

from threading import Thread
import time

class MyThread(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.start()

    def run(self):
        while (True):
            self.foo()
            time.sleep(1)

    def foo(self):
        print("foo !")

my = None

while True:
    user_input = raw_input("What do I do ? ")

    if user_input == "start thread":
        #Will start a threat that prints foo every second.
        if my == None: 
            print("Starting thread...")
            my = MyThread()
        else:
            print("Thread is already started.")

    elif user_input == "hello":
        print("Hello !")

    else:
        print("This is not a correct command.")

【讨论】:

  • 无限递归可能最终会导致问题(堆栈溢出,方便:P),但我认为这不是@sohomangue 面临的直接问题
  • 我不知道无限使用计时器是错误的,我会解决这个问题!然而,使用ˋtime.sleep()`并没有改变输出,程序仍然等待下一个控制台打印打印“foo!”而不是每秒打印一次。
  • 我修改了我的代码,让它像你想要的那样为我工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 2015-01-22
  • 2022-06-24
  • 1970-01-01
  • 2022-10-05
  • 2015-10-24
  • 2016-12-19
相关资源
最近更新 更多