asr-demo.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import pty
  2. import os
  3. import re
  4. def read_with_pty(demo_path):
  5. pattern = re.compile(r"\('([^']*)',\s*'([^']*)'\)")
  6. # 模拟终端运行程序
  7. master, slave = pty.openpty()
  8. pid = os.fork()
  9. if pid == 0:
  10. # 子进程:执行程序,输出到模拟终端
  11. os.dup2(slave, 1)
  12. os.dup2(slave, 2)
  13. os.close(master)
  14. os.close(slave)
  15. os.execv(demo_path, [demo_path])
  16. else:
  17. # 父进程:读取模拟终端的输出
  18. os.close(slave)
  19. print("模拟终端启动,监听中...")
  20. with os.fdopen(master, 'r', encoding='utf-8', errors='ignore') as f:
  21. for line in f:
  22. line = line.strip()
  23. if not line:
  24. continue
  25. match = pattern.match(line)
  26. if match:
  27. print(f"识别文本:{match.group(1)} | 拼音:{match.group(2)}")
  28. else:
  29. print(f"【原始】:{line}")
  30. os.waitpid(pid, 0)
  31. if __name__ == "__main__":
  32. DEMO_PATH = os.path.abspath("../audio_check_demo")
  33. read_with_pty(DEMO_PATH)