繁体   English   中英

为什么在另一个线程中启动异步事件循环会与我的 pipe 混淆?

[英]Why does starting an asyncio event loop in another thread mess with my pipe?

我有 2 个进程。 我想write.py通过 Linux pipe 向read.py写一条消息。

### write.py
import subprocess
import asyncio
from threading import Thread

# !-- Offending code here. --!
# loop = asyncio.new_event_loop()
# def side_thread(loop):
#     asyncio.set_event_loop(loop)
#     loop.run_forever()
# thread = Thread(target=side_thread, args=(loop,))
# thread.start()

notify_proc = subprocess.Popen("python read.py".split(), stdin=subprocess.PIPE)

notify_proc.stdin.write("hello\n".encode("utf-8"))
### read.py
import sys

for line in sys.stdin:
  print("Got something!")
  print(line)

如给定的,当我运行python write.py时,我得到了预期的 output:

Got something!
hello

但是当我取消注释有问题的代码时,我没有得到任何 output。 为什么?

  • Python 3.9.7
  • Linux 5.4.72-microsoft-standard-WSL2 x86_64

在刷新缓冲区或进程结束之前,您的缓冲区不会被发送过来,并且只要非守护线程正在运行,进程就不会结束。 在短期内,您可以添加notify_proc.stdin.flush() ,但是您将多处理、线程和异步混合使用会导致流泪。 你到底想在这里做什么?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM