diff --git a/pydu/cmd.py b/pydu/cmd.py index 1ae2858..de2f0d0 100644 --- a/pydu/cmd.py +++ b/pydu/cmd.py @@ -23,6 +23,26 @@ def run(cmd, wait=True, shell=True, timeout=0, timeinterval=1): return p.poll(), stdout +def run_with_en_env(cmd, wait=True, shell=True, timeout=0, timeinterval=1): + """ + Run cmd with English character sets environment, so that the output will + be in English. + Parameters are same with `run`. + """ + if WINDOWS: + with chcp(437): + return run(cmd, wait=wait, shell=shell, + timeout=timeout, timeinterval=timeinterval) + else: + export_lang = 'export LANG=en_US.UTF-8' + if isinstance(cmd, list): + pre_cmd = [export_lang, ';'] + else: + pre_cmd = export_lang + '; ' + return run(pre_cmd + cmd, wait=wait, shell=shell, + timeout=timeout, timeinterval=timeinterval) + + if PY2 and WINDOWS: # enable passing unicode arguments from command line in Python 2.x # https://stackoverflow.com/questions/846850/read-unicode-characters diff --git a/tests/test_cmd.py b/tests/test_cmd.py index 9935e56..73c4150 100644 --- a/tests/test_cmd.py +++ b/tests/test_cmd.py @@ -3,7 +3,7 @@ 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 +from pydu.cmd import run, run_with_en_env, cmdline_argv def test_run(): @@ -20,6 +20,14 @@ def test_run(): assert 'timeout' in output +def test_run_with_en_env(): + _, output = run_with_en_env('nocmd') + assert output.decode('ascii') + + _, output = run_with_en_env(['nocmd']) + assert output.decode('ascii') + + def test_cmdline_argv(): argv = cmdline_argv() for s in argv[1:]: