我正在学习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.
答案 0 :(得分:-1)
你做错了。 run()方法必须是一个无限循环,而不是无限递归:
[char[]]$replace = '!@#$%^&*(){}[]":;,<>/|\+=`~ '''
$regex = ($replace | % {[regex]::Escape($_)}) -join '|'
Get-ChildItem -recurse |
Where-Object { $_.Name -match $RegEx} |
Rename-Item -NewName {$_.Name -replace $RegEx, '_'} -whatif