def _detect_encoding(stdout):
        """
        Detect the default encoding for the terminal's output.
        :return: string: encoding string
        """
        if hasattr(stdout, 'encoding') and stdout.encoding:
            return stdout.encoding

        if os.environ.get('LANG'):
            encoding = os.environ.get('LANG').split('.')[-1]

            # validate the encoding string
            ret = None
            try:
                ret = codecs.lookup(encoding)
            except LookupError:
                pass
            if ret:
                return encoding

        return locale.getpreferredencoding()