convert.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Author: hywell
  5. @Email: hywell.28@gmail.com
  6. @Blog: iassas.com
  7. @Date: 2019/10/16 13:57
  8. """
  9. import sys
  10. from lib.core.setting import IS_WIN
  11. from lib.core.setting import UNICODE_ENCODING
  12. def single_time_warn_message(message):
  13. """
  14. Cross-linked function
  15. """
  16. sys.stdout.write(message)
  17. sys.stdout.write("\n")
  18. sys.stdout.flush()
  19. def stdout_encode(data):
  20. try:
  21. data = data or ""
  22. # Reference: http://bugs.python.org/issue1602
  23. if IS_WIN:
  24. output = data.encode(sys.stdout.encoding, "replace")
  25. if '?' in output and '?' not in data:
  26. warn_msg = "cannot properly display Unicode characters "
  27. warn_msg += "inside Windows OS command prompt "
  28. warn_msg += "(http://bugs.python.org/issue1602). All "
  29. warn_msg += "unhandled occurances will result in "
  30. warn_msg += "replacement with '?' character. Please, find "
  31. warn_msg += "proper character representation inside "
  32. warn_msg += "corresponding output files. "
  33. single_time_warn_message(warn_msg)
  34. ret = output
  35. else:
  36. ret = data.encode(sys.stdout.encoding)
  37. except Exception:
  38. ret = data.encode(UNICODE_ENCODING) if isinstance(data, str) else data
  39. return ret