From 9093d0d691c42eb5602df93ea81f5ffec17b5662 Mon Sep 17 00:00:00 2001 From: Erik Osheim Date: Wed, 26 Aug 2009 10:07:48 -0400 Subject: [PATCH] add method for safer text decoding --HG-- branch : pmacs2 --- util.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/util.py b/util.py index 008c58c..5e0101c 100644 --- a/util.py +++ b/util.py @@ -2,6 +2,7 @@ import os import pwd import re import regex +from subprocess import Popen, PIPE, STDOUT # character buffers use sequences like [r:d]foo[d:d] to indicate that foo # should be fg=red,bg=default. as such, we have to escape \, [ and ]. @@ -134,3 +135,20 @@ except: def __repr__(self): return 'defaultdict(%s, %s)' % (self.default_factory, dict.__repr__(self)) + +def decode(s): + for format in ('utf-8', 'latin-1'): + try: + return s.decode(format) + except: + pass + return s.decode('ascii', 'replace') + +def communicate(cmd, stdin=None, stderr=False, shell=True): + if stderr: + pipe = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=shell) + else: + pipe = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=shell) + out, err = pipe.communicate(input=stdin) + result = pipe.wait() + return result, decode(out or ''), decode(err or '')