Python sh库交互式回调对无换行提示行未触发问题求助
问题根源
sh库默认使用行缓冲模式处理目标进程的输出,只有收到完整的换行符才会触发交互回调。你使用的echo -n输出的提示符不带换行,会一直卡在缓冲区中无法被回调捕获,就会出现无后续输出的问题。
可运行的交互示例
你的shell脚本example1不需要做任何修改,保持原有带echo -n的逻辑即可,修改Python代码如下:
# test_example1.py import sh def interact(char, stdin): # 维护缓存拼接零散的字节输出 if not hasattr(interact, "output_cache"): interact.output_cache = [] interact.output_cache.append(char) current_content = "".join(interact.output_cache) # 匹配到无换行的提示符时写入输入 if "Hello, who am I talking to?:" in current_content: stdin.put("me\n") # 匹配到最终输出后结束交互 if "It's nice to meet you me" in current_content: print(f">> 最终输出: {current_content.strip()}") return True # 遇到换行时打印完整行 if char == "\n": print(f">> 行输出: {current_content.strip()}") interact.output_cache.clear() print("-Start-") # 关键参数配置 response = sh.example1( _out=interact, _bg=True, _pty=True, # 分配伪终端,模拟交互环境,关闭进程侧全缓冲 _out_bufsize=1 # 按单字节触发回调,无需等待换行 ) response.wait() print("-End-")
运行输出
-Start- >> 行输出: Good Morning, sir. >> 最终输出: Hello, who am I talking to?:It's nice to meet you me -End-
参数说明
_pty=True:为目标shell脚本分配伪终端,让脚本认为自己运行在真实的交互终端中,会主动flush不带换行的输出内容,不会滞留在进程内部缓冲区。_out_bufsize=1:将sh库的输出缓冲区大小设为1字节,每收到1字节的输出就触发一次回调,不再等待换行符,即可识别到无换行的提示符。如果目标进程输出量很大,可以根据实际情况调大该数值,只要保证小于你要匹配的最短字符串长度即可,平衡性能和识别及时性。
内容的提问来源于stack exchange,提问作者asterio gonzalez
相关产品推荐
相关产品推荐

