如何通过定期更新管理实时输入

时间:2017-08-14 16:49:03

标签: python

我在位置(0,0)有一个区块。定期(比如每1秒),块的y坐标将随机更新+/- 1。

每次用户输入字符(+/-)时,x坐标将在用户输入时更新+/- 1。

如果它只是x坐标,我可以创建一个while循环,当input()获得一个值时,它会进入下一次迭代。

但是我如何处理定期更新以及实时输入(可以随时出现?)

1 个答案:

答案 0 :(得分:1)

Threading是你的朋友:

import time
from threading import Thread


# This defines the thread that handles console input
class UserInputThread(Thread):
    def __init__ (self):
        Thread.__init__(self)

    # Process user input here:
    def run(self):
        while True:
            text = input("input: ")
            print("You said", text)
            # Exit the thread
            if text == "exit":
                return


console_thread = UserInputThread()
console_thread.start()

while True:
    time.sleep(5)
    print("function")
    # If the thread is dead, the programme will exit when the current iteration of the while loop ends.
    if not console_thread.is_alive():
        break

UserInputThread在后​​台运行并处理用户输入。 print("function")可以是您在主线程中需要做的任何逻辑。

相关问题