在Python中从控制台获取异步输入

问题描述 投票:1回答:1

我正在做一个python程序,它在工作时可以从终端获得输入。

例如,当运行一些进程时,他可以从终端命令中进行异步控制,并且他不会因为用户的输入而停止。

如何在python中做到这一点?

python multithreading asynchronous user-input
1个回答
0
投票

你不能使用 asyncio 模块与 input()因为 input() 将阻止事件循环。要做你想做的事,你应该使用 multithreading 模块代替。

看看这个例子。

import time
from threading import Thread


def another_thread():
    while True:
        time.sleep(2)
        print("Working...\n")


def main_thread():
    while True:
        x = input("Press a key: \n")
        if x == "q":
            break


if __name__ == '__main__':
    # create another Thread object
    # daemon means that it will stop if the Main Thread stops
    th = Thread(target=another_thread, daemon=True)
    th.start()  # start the side Thread
    main_thread()  # start main logic
© www.soinside.com 2019 - 2024. All rights reserved.