如何使用async在Python3中从子进程进行非阻塞写入和读取?

如何使用async在Python3中从子进程进行非阻塞写入和读取?,python,multithreading,asynchronous,async-await,nonblocking,Python,Multithreading,Asynchronous,Async Await,Nonblocking,如何使用async在Python3中从子进程进行非阻塞写入和读取 我创建了多线程代码,它运行子进程,而不是将子进程的stdin复制到stdin,将子进程stdout复制到stdout,仅此而已 有没有可能在不使用多线程的情况下编写相同的代码?多线程非常消耗cpu,并且使用异步——我在异步方面没有经验,或者非常弱(在Python方面非常好)。你能解释一下怎么做,或者给出一些代码示例,说明如何重写这段代码吗 import queue import sys import subprocess imp

如何使用async在Python3中从子进程进行非阻塞写入和读取

我创建了多线程代码,它运行子进程,而不是将子进程的stdin复制到stdin,将子进程stdout复制到stdout,仅此而已

有没有可能在不使用多线程的情况下编写相同的代码?多线程非常消耗cpu,并且使用异步——我在异步方面没有经验,或者非常弱(在Python方面非常好)。你能解释一下怎么做,或者给出一些代码示例,说明如何重写这段代码吗

import queue
import sys

import subprocess
import threading

import time


# copy stream into threading queue
def read_into_queue(stream, queue):
    while True:
        line = stream.readline()
        if not line:
            break
        queue.put_nowait(line)


if __name__ == '__main__':
    child_process = subprocess.Popen('cat',
                                     universal_newlines=True,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE)

    # start thread coping stdin to child process stdin
    queue_input = queue.Queue()
    thread_input = threading.Thread(target=read_into_queue, args=(sys.stdin, queue_input), daemon=True)
    thread_input.start()

    # start thread coping child process stdout to stdout
    queue_output = queue.Queue()
    thread_output = threading.Thread(target=read_into_queue, args=(child_process.stdout, queue_output), daemon=True)
    thread_output.start()

    # check if something on queue
    while True:
        empty = 0

        try:
            input_line = queue_input.get_nowait()
            child_process.stdin.write(input_line)
            child_process.stdin.flush()
        except queue.Empty:
            empty += 1

        try:
            output_line = queue_output.get_nowait()
            sys.stdout.write(output_line)
            sys.stdout.flush()
        except queue.Empty:
            empty += 1

        # make cpu little idle
        if empty == 2:
            time.sleep(0.05)