run_with_clean_log.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env python
  2. import sys
  3. import subprocess
  4. from io import RawIOBase
  5. class StreamFilter(RawIOBase):
  6. def __init__(self, conds, stream):
  7. super().__init__()
  8. self.conds = conds
  9. self.stream = stream
  10. def readinto(self, _):
  11. pass
  12. def write(self, msg):
  13. if all(cond(msg) for cond in self.conds):
  14. self.stream.write(msg)
  15. else:
  16. pass
  17. class CleanLog(object):
  18. def __init__(self, filter_, stream_name):
  19. self.filter = filter_
  20. self.stream_name = stream_name
  21. self.old_stream = getattr(sys, stream_name)
  22. def __enter__(self):
  23. setattr(sys, self.stream_name, self.filter)
  24. def __exit__(self, exc_type, exc_value, traceback):
  25. setattr(sys, self.stream_name, self.old_stream)
  26. if __name__ == '__main__':
  27. if len(sys.argv) < 2:
  28. raise TypeError("请指定需要运行的脚本!")
  29. tar_file = sys.argv[1]
  30. gdal_filter = StreamFilter([
  31. lambda msg: "Sum of Photometric type-related color channels and ExtraSamples doesn't match SamplesPerPixel." not in msg
  32. ], sys.stdout)
  33. with CleanLog(gdal_filter, 'stdout'):
  34. proc = subprocess.Popen(
  35. ["python", tar_file],
  36. stderr=subprocess.STDOUT,
  37. stdout=subprocess.PIPE,
  38. text=True)
  39. while True:
  40. try:
  41. out_line = proc.stdout.readline()
  42. if out_line == '' and proc.poll() is not None:
  43. break
  44. if out_line:
  45. print(out_line, end='')
  46. except KeyboardInterrupt:
  47. import signal
  48. proc.send_signal(signal.SIGINT)