简体   繁体   English

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

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

I have 2 processes.我有 2 个进程。 I would like write.py to write a message to read.py through a Linux pipe.我想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)

As given, when I run python write.py , I get the expected output:如给定的,当我运行python write.py时,我得到了预期的 output:

Got something!
hello

But when I uncomment the offending code, I don't get any output.但是当我取消注释有问题的代码时,我没有得到任何 output。 Why?为什么?

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

Your buffer won't get sent over until the buffer is flushed or the process ends, and the process will not end as long as a non-daemon thread is running.在刷新缓冲区或进程结束之前,您的缓冲区不会被发送过来,并且只要非守护线程正在运行,进程就不会结束。 In the short term, you can add notify_proc.stdin.flush() , but your mixing of multiprocessing, threading and asyncio is going to lead to tears.在短期内,您可以添加notify_proc.stdin.flush() ,但是您将多处理、线程和异步混合使用会导致流泪。 What on earth are you trying to do here?你到底想在这里做什么?

暂无
暂无

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

相关问题 为什么我的队列挂着异步事件循环 - Why is my queue hanging with asyncio event loop 为什么异步事件循环会抑制Windows上的KeyboardInterrupt? - Why does the asyncio's event loop suppress the KeyboardInterrupt on Windows? 为什么asyncio.get_event_loop方法检查当前线程是否为主线程? - Why asyncio.get_event_loop method checks if the current thread is the main thread? 除非你使用set_event_loop,为什么asyncio子进程与创建的事件循环的行为不同? - Why does asyncio subprocess behave differently with created event loop unless you set_event_loop? asyncio 主线程如何管理同时运行事件循环和协程? - How does asyncio main thread manage running either the event loop and coroutines at the same time? RuntimeError: 线程 'Thread-1' 中没有当前事件循环,多线程和异步错误 - RuntimeError: There is no current event loop in thread 'Thread-1' , multithreading and asyncio error Flask asyncio aiohttp - RuntimeError:线程'Thread-2'中没有当前事件循环 - Flask asyncio aiohttp - RuntimeError: There is no current event loop in thread 'Thread-2' asyncio 事件循环是否只运行任务? - Does the asyncio event loop only run tasks? 在主线程运行的asyncio事件循环中运行无限循环 - run infinite loop in asyncio event loop running off the main thread asyncio:为什么取消任务会导致取消添加到事件循环中的其他任务? - asyncio: Why does cancelling a task lead to cancellation of other tasks added into the event loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM