Просмотр исходного кода

Fix the pty output format error.

prc 1 год назад
Родитель
Сommit
e8cfef9f28
2 измененных файлов с 42 добавлено и 5 удалено
  1. 40 4
      build_all.py
  2. 2 1
      build_and_release.py

+ 40 - 4
build_all.py

@@ -1,4 +1,5 @@
 import os
+import re
 import sys
 
 from winpty import PtyProcess
@@ -49,16 +50,51 @@ class BuildAll:
             pass
         return True
 
-    @staticmethod
-    def __execute_cmd_with_pty(cmd, cwd=None):
+    def __execute_cmd_with_pty(self, cmd, cwd=None):
+        counter_output_is_all_none: int = 0
         process = PtyProcess.spawn(["cmd", "/c", cmd], cwd=cwd)
+        process.setwinsize(20, 9999)
         while process.isalive():
             try:
-                output = process.read()
-                print(output, end='')
+                output: str = process.readline()
+                output = self.__remove_ansi_escape_codes(output)
+                output = self.__remove_leading_newlines(output)
+                if output in ["", " ", "\n", "\r\n", "\n\r"]:
+                    if counter_output_is_all_none != 0:
+                        continue
+                    else:
+                        counter_output_is_all_none += 1
+                        print("\n", end='')
+                        continue
+                else:
+                    counter_output_is_all_none = 0
+                output = self.__remove_ending_newlines(output)
+                print(output, end='\n')
             except EOFError:
                 break  # 当伪终端关闭时跳出循环
 
+    @staticmethod
+    def __remove_ansi_escape_codes(s):
+        ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
+        return ansi_escape.sub('', s)
+
+    @staticmethod
+    def __remove_leading_newlines(s):
+        while s.startswith(('\n\r', '\r\n', '\n', '\r')):
+            for seq in ['\n\r', '\r\n', '\n', '\r']:
+                if s.startswith(seq):
+                    s = s[len(seq):]
+        return s
+
+    @staticmethod
+    def __remove_ending_newlines(s):
+        sequences = ['\n\r', '\r\n', '\n', '\r']
+        while s.endswith(tuple(sequences)):
+            for seq in sequences:
+                if s.endswith(seq):
+                    s = s[:-len(seq)]
+        return s
+
 
 if __name__ == "__main__":
     builder = BuildAll()

+ 2 - 1
build_and_release.py

@@ -20,9 +20,10 @@ class BuildAndRelease:
                 command += f"-python_env_name={self.user_input}"
             # 使用PtyProcess来运行命令
             proc = PtyProcess.spawn(["powershell", "-Command", command])
+            proc.setwinsize(20, 9999)
             # 读取输出并打印到当前终端
             while True:
-                data = proc.read()
+                data = proc.readline()
                 if not data:
                     break
                 print(data, end='')