Python使用less分页器遇EOF后界面冻结,如何解决该问题?
解决less分页器冻结问题
问题根源:当你写完内容后未关闭子进程的stdin管道时,less会认为还有后续输入,在滚动到输出末尾时会一直等待新数据,导致界面无法响应操作。
解决步骤:
- 所有内容写入并
flush完成后,关闭子进程的stdin管道,让less明确输入已结束,之后再调用wait()等待退出。
完整示例代码:
import subprocess a_process = subprocess.Popen(["less"], stdin=subprocess.PIPE) # 写入多行内容 a_process.stdin.write("hello\n".encode()) a_process.stdin.write("second line\n".encode()) a_process.stdin.write("end of content\n".encode()) a_process.stdin.flush() # 关键操作:关闭stdin管道 a_process.stdin.close() # 等待less退出 a_process.wait()
这样修改后,用户滚动到输出末尾时,less会正常识别输入结束,允许用户上翻或按q退出,不会出现冻结情况。
内容的提问来源于stack exchange,提问作者eftshift0
相关产品推荐
相关产品推荐

