From 43ad610a663a5a2a9229d7b435b8585ada645a5d Mon Sep 17 00:00:00 2001 From: Stefano Rivera Date: Wed, 4 Sep 2019 12:25:54 -0300 Subject: [PATCH] Add encoding support to our Popen wrapper --- ubuntutools/misc.py | 4 ++-- ubuntutools/subprocess.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/ubuntutools/misc.py b/ubuntutools/misc.py index f61a84a..4ccbb15 100644 --- a/ubuntutools/misc.py +++ b/ubuntutools/misc.py @@ -50,7 +50,7 @@ def system_distribution_chain(): if len(_system_distribution_chain) == 0: try: p = Popen(('dpkg-vendor', '--query', 'Vendor'), - stdout=PIPE) + stdout=PIPE, encoding='utf-8') _system_distribution_chain.append(p.communicate()[0].strip()) except OSError: print('Error: Could not determine what distribution you are running.') @@ -61,7 +61,7 @@ def system_distribution_chain(): p = Popen(('dpkg-vendor', '--vendor', _system_distribution_chain[-1], '--query', 'Parent'), - stdout=PIPE) + stdout=PIPE, encoding='utf-8') parent = p.communicate()[0].strip() # Don't check return code, because if a vendor has no # parent, dpkg-vendor returns 1 diff --git a/ubuntutools/subprocess.py b/ubuntutools/subprocess.py index 1d9e90a..e3772f2 100644 --- a/ubuntutools/subprocess.py +++ b/ubuntutools/subprocess.py @@ -6,6 +6,8 @@ module whose defaults better line up with our tastes. In particular, it: - Adds support for the restore_signals flag if subprocess itself doesn't support it + - Adds support for the encoding flag if subprocess itself doesn't + support it - Defaults close_fds to True """ @@ -13,6 +15,7 @@ In particular, it: from __future__ import absolute_import import inspect +import codecs import signal import subprocess import sys @@ -28,8 +31,10 @@ class Popen(subprocess.Popen): kwargs.setdefault('close_fds', True) if sys.version_info[0] >= 3: getargs = inspect.getfullargspec + encoding = None else: getargs = inspect.getargspec + encoding = kwargs.pop('encoding', None) if 'restore_signals' not in getargs(subprocess.Popen.__init__)[0]: given_preexec_fn = kwargs.pop('preexec_fn', None) @@ -47,6 +52,11 @@ class Popen(subprocess.Popen): kwargs['preexec_fn'] = preexec_fn subprocess.Popen.__init__(self, *args, **kwargs) + if encoding is not None: + for channel in ('stdin', 'stdout', 'stderr'): + fd = getattr(self, channel) + if fd is not None: + setattr(self, channel, codecs.EncodedFile(fd, encoding)) # call, check_call, and check_output are copied directly from the