【问题标题】:Why does starting an asyncio event loop in another thread mess with my pipe?为什么在另一个线程中启动异步事件循环会弄乱我的管道?
【发布时间】:2021-11-21 01:52:00
【问题描述】:

我有 2 个进程。我希望write.py 通过 Linux 管道向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 时,我得到了预期的输出:

Got something!
hello

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

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

【问题讨论】:

    标签: python subprocess python-asyncio


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 2015-12-13
      • 1970-01-01
      • 2018-02-18
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多