gpt4 book ai didi

python-3.x - 如何中止在 python3 中等待 sys.stdin?

转载 作者:行者123 更新时间:2023-12-04 19:43:09 47 4
gpt4 key购买 nike

我正在运行一个包含两个线程的脚本,一个从子进程读取的线程,以及一个主线程。

在主线程中,我正在从 stdin 读取数据,如下所示:

for line in sys.stdin:

if proc.poll() != None:
break

proc.stdin.write(line)
proc.stdin.flush()

<other things happen here>

(proc是外部子进程)

现在,这很好用,直到我想关闭我的程序。当另一个线程中的进程退出时,我希望整个程序停止,但主线程仍在等待输入某些内容到stdin。我怎样才能中止它?

基本上,我希望 stdin 收到 EOF 信号,但我不知道该怎么做。

最佳答案

我会交换线程。从主线程中的子进程读取,并在另一个线程中执行阻塞 sys.stdin 内容。这样您就可以将 daemon=True 传递给 threading.Thread,这会在主线程退出时让线程退出。

关于python-3.x - 如何中止在 python3 中等待 sys.stdin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38423113/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com