【发布时间】: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