From 1e92d66d5792ff86d3b5a7be003204c83ae005c9 Mon Sep 17 00:00:00 2001 From: Yosuke Mizutani Date: Sun, 25 Oct 2015 23:11:14 +0900 Subject: [PATCH] refactored execute_command --- src/mog_commons/__init__.py | 2 +- src/mog_commons/command.py | 21 +++++++++++++++------ tests/mog_commons/test_command.py | 2 ++ 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/mog_commons/__init__.py b/src/mog_commons/__init__.py index 1c98a23..850505a 100644 --- a/src/mog_commons/__init__.py +++ b/src/mog_commons/__init__.py @@ -1 +1 @@ -__version__ = '0.1.9' +__version__ = '0.1.10' diff --git a/src/mog_commons/command.py b/src/mog_commons/command.py index fe7f8c4..b97f778 100644 --- a/src/mog_commons/command.py +++ b/src/mog_commons/command.py @@ -4,6 +4,7 @@ import os import errno import subprocess +import six from mog_commons.string import is_unicode from mog_commons.functional import oget @@ -12,17 +13,25 @@ # Process operations # def __convert_args(args, shell, cmd_encoding): - xs = [] + # Note: workaround for http://bugs.python.org/issue8513 + workaround = shell and sys.version_info[:2] == (3, 2) and not sys.platform == 'win32' + + if isinstance(args, six.string_types): + # input as string + s = args.encode(cmd_encoding) + if workaround: + return ['/bin/sh', '-c', s], False + else: + return args, shell + + # input as list + xs = ['/bin/sh', '-c'] if workaround else [] if shell: args = [subprocess.list2cmdline(args)] - if shell and sys.version_info[:2] == (3, 2) and not sys.platform == 'win32': - # Note: workaround for http://bugs.python.org/issue8513 - xs = ['/bin/sh', '-c'] - shell = False for a in args: assert is_unicode(a), 'cmd must be unicode string, not %s' % type(a).__name__ xs.append(a.encode(cmd_encoding)) - return xs, shell + return xs, shell and not workaround def execute_command(args, shell=False, cwd=None, env=None, stdin=None, stdout=None, stderr=None, cmd_encoding='utf-8'): diff --git a/tests/mog_commons/test_command.py b/tests/mog_commons/test_command.py index 713a2d7..293d5da 100644 --- a/tests/mog_commons/test_command.py +++ b/tests/mog_commons/test_command.py @@ -10,6 +10,8 @@ class TestCommand(unittest.TestCase): def test_execute_command(self): self.assertEqual(execute_command(['exit', '2'], shell=True), 2) + self.assertEqual(execute_command('exit 3', shell=True), 3) + self.assertEqual(execute_command(['/bin/sh', '-c', 'exit 4'], shell=False), 4) def test_capture_command(self): self.assertEqual(capture_command(['echo', 'あいう'], shell=True), (0, 'あいう\n'.encode('utf-8'), b''))