python subprocess多次写入命令并多次获取输出

import subprocess
import select
import time
 
# 创建一个Popen对象
process = subprocess.Popen(['bash'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
    # 发送命令并立即读取输出(非阻塞方式)
    for cmd in ['echo Hello, World!', 'pwd', 'ls']:
        process.stdin.write(f'{cmd}\n')  # 发送命令
        process.stdin.flush()  # 确保命令被发送出去
        time.sleep(0.1)  # 等待一小段时间让命令执行(可选)
        while select.select([process.stdout], [], [], 0.1)[0]:  # 非阻塞读取输出直到有数据可读或超时
            output = process.stdout.readline()  # 读取一行输出
            print(output, end='')  # 打印输出(不带换行)
finally:
    process.stdin.close()  # 关闭输入流以通知bash进程结束输入
    process.wait()

注意,这段代码在linux会执行成功

但是在windows会执行失败

Traceback (most recent call last):
  File "C:\Users\xxx\desktop\exer.py", line 308, in <module>
    while select.select([process.stdout], [], [], 0.1)[0]:  # 非阻塞读取输出直到有数据可读或超时
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OSError: [WinError 10093] Either the application has not called WSAStartup, or WSAStartup failed

 

posted @ 2025-05-23 16:20  我的腹肌不见了  阅读(46)  评论(0)    收藏  举报