From 0b0a0ba2f7773cee69faf7565883c57f977f14a5 Mon Sep 17 00:00:00 2001 From: Prodesire Date: Fri, 22 Dec 2017 18:54:30 +0800 Subject: [PATCH] add cmd.chcp for Windows --- pydu/cmd.py | 19 +++++++++++++++++++ tests/test_cmd.py | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/pydu/cmd.py b/pydu/cmd.py index e01f5db..fcaf21d 100644 --- a/pydu/cmd.py +++ b/pydu/cmd.py @@ -61,3 +61,22 @@ if PY2 and WINDOWS: else: def cmdline_argv(): return sys.argv + + +if WINDOWS: + from ctypes import windll + + class chcp(object): + """ + Context manager which sets the active code page number. + It could also be used as function. + """ + def __init__(self, code): + self.origin_code = windll.kernel32.GetConsoleOutputCP() + windll.kernel32.SetConsoleOutputCP(code) + + def __enter__(self): + pass + + def __exit__(self, exc_type, exc_val, exc_tb): + windll.kernel32.SetConsoleOutputCP(self.origin_code) diff --git a/tests/test_cmd.py b/tests/test_cmd.py index 4b44513..fb2c385 100644 --- a/tests/test_cmd.py +++ b/tests/test_cmd.py @@ -1,4 +1,6 @@ import sys +import pytest +from pydu.platform import WINDOWS from pydu.compat import string_types from pydu.string import safeunicode from pydu.cmd import run, cmdline_argv @@ -22,3 +24,20 @@ def test_cmdline_argv(): argv = cmdline_argv() for s in argv[1:]: assert isinstance(s, string_types) + + +@pytest.mark.skipif(not WINDOWS, reason='Not support non windows') +def test_chcp(): + from pydu.cmd import chcp + from ctypes import windll + + origin_code = windll.kernel32.GetConsoleOutputCP() + with chcp(437): + assert windll.kernel32.GetConsoleOutputCP() == 437 + assert windll.kernel32.GetConsoleOutputCP() == origin_code + + try: + chcp(437) + assert windll.kernel32.GetConsoleOutputCP() == 437 + finally: + windll.kernel32.SetConsoleOutputCP(origin_code)