Bram Moolenaar | 2c7292d | 2017-03-05 17:43:31 +0100 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # -*- coding: utf-8 -*- |
| 3 | |
| 4 | # Test program for :make, :grep and :cgetfile. |
| 5 | |
| 6 | from __future__ import print_function, unicode_literals |
| 7 | import locale |
| 8 | import io |
| 9 | import sys |
| 10 | |
| 11 | def set_output_encoding(enc=None): |
| 12 | """Set the encoding of stdout and stderr |
| 13 | |
| 14 | arguments: |
| 15 | enc -- Encoding name. |
| 16 | If omitted, locale.getpreferredencoding() is used. |
| 17 | """ |
| 18 | if enc is None: |
| 19 | enc = locale.getpreferredencoding() |
| 20 | |
| 21 | def get_text_writer(fo, **kwargs): |
| 22 | kw = dict(kwargs) |
| 23 | kw.setdefault('errors', 'backslashreplace') # use \uXXXX style |
| 24 | kw.setdefault('closefd', False) |
| 25 | |
| 26 | if sys.version_info[0] < 3: |
| 27 | # Work around for Python 2.x |
| 28 | # New line conversion isn't needed here. Done in somewhere else. |
| 29 | writer = io.open(fo.fileno(), mode='w', newline='', **kw) |
| 30 | write = writer.write # save the original write() function |
| 31 | enc = locale.getpreferredencoding() |
| 32 | def convwrite(s): |
| 33 | if isinstance(s, bytes): |
| 34 | write(s.decode(enc)) # convert to unistr |
| 35 | else: |
| 36 | write(s) |
| 37 | try: |
| 38 | writer.flush() # needed on Windows |
| 39 | except IOError: |
| 40 | pass |
| 41 | writer.write = convwrite |
| 42 | else: |
| 43 | writer = io.open(fo.fileno(), mode='w', **kw) |
| 44 | return writer |
| 45 | |
| 46 | sys.stdout = get_text_writer(sys.stdout, encoding=enc) |
| 47 | sys.stderr = get_text_writer(sys.stderr, encoding=enc) |
| 48 | |
| 49 | |
| 50 | def main(): |
| 51 | enc = 'utf-8' |
| 52 | if len(sys.argv) > 1: |
| 53 | enc = sys.argv[1] |
| 54 | set_output_encoding(enc) |
| 55 | |
| 56 | message_tbl = { |
| 57 | 'utf-8': 'ÀÈÌÒÙ こんにちは 你好', |
| 58 | 'latin1': 'ÀÈÌÒÙ', |
| 59 | 'cp932': 'こんにちは', |
| 60 | 'cp936': '你好', |
| 61 | } |
| 62 | |
| 63 | print('Xfoobar.c(10) : %s (%s)' % (message_tbl[enc], enc)) |
| 64 | |
| 65 | |
| 66 | if __name__ == "__main__": |
| 67 | main() |