如何从yowsup-cli子进程获取输出并实现变量交互?
解决yowsup-cli交互式进程的输入输出问题
你遇到的核心问题其实很明确:yowsup-cli的demos模式是交互式命令行工具,它会持续运行并等待你的输入,而你之前用的proc.communicate()是一次性等待进程终止后才读取所有输出——但这个进程根本不会自动终止,自然拿不到实时返回,也没法持续交互。
下面是针对这个场景的完整解决方案:
核心思路
我们要放弃一次性的communicate(),改为实时监听进程的stdout/stderr输出,同时保留向进程stdin写入输入的能力,实现双向交互。因为Python的subprocess在处理流式输出时容易阻塞,所以最好用线程来分别处理输出读取,避免主线程卡住。
完整示例代码
import subprocess import threading def read_stream(stream, output_handler): """线程函数:实时读取流内容并调用处理函数""" for line in iter(stream.readline, b''): # 解码为字符串并去除首尾空白 output_handler(line.decode('utf-8').strip()) stream.close() def process_yowsup_output(line): """自定义处理yowsup-cli的返回内容""" print(f"[yowsup返回] {line}") # 这里可以根据输出做逻辑判断,比如检测到特定提示后发送下一个命令 # 启动yowsup-cli进程 cmd = "python /root/yowsup/yowsup-cli demos --yowsup --config config.json" proc = subprocess.Popen( cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, # 把stderr合并到stdout,统一处理 stdin=subprocess.PIPE, bufsize=1, # 行缓冲,确保输出实时刷新 universal_newlines=True # 文本模式,自动处理编码 ) # 启动线程监听输出 output_thread = threading.Thread(target=read_stream, args=(proc.stdout, process_yowsup_output)) output_thread.daemon = True # 主线程结束时自动终止子线程 output_thread.start() # 示例:向yowsup-cli发送输入 try: # 模拟终端输入,记得加换行符 test_input = "your_command_here\n" proc.stdin.write(test_input) proc.stdin.flush() # 强制刷新缓冲区,确保输入立即发送 # 可以在这里添加更多交互逻辑,比如根据输出等待或发送新命令 # 等待进程结束(如果需要) proc.wait() except KeyboardInterrupt: # 处理用户中断,优雅终止进程 proc.terminate() proc.wait()
关键细节说明
- 线程读取输出:用单独线程处理stdout读取,避免主线程被阻塞,这样能实时获取yowsup-cli的每一行返回。
- 缓冲配置:
bufsize=1和universal_newlines=True确保输出按行实时刷新,不会攒到缓冲区满才输出。 - 输入发送:向
proc.stdin写入内容后必须调用flush(),否则输入会被缓冲,无法立即传递给yowsup-cli。 - 合并stderr:把stderr重定向到stdout是为了统一处理所有输出,如果需要分开处理,也可以给stderr单独开一个监听线程。
这样修改后,你就能实时获取yowsup-cli的返回结果,同时也能随时向它传递输入变量了。
内容的提问来源于stack exchange,提问作者sinaps1
相关产品推荐
相关产品推荐

