當前位置: 首頁>>代碼示例>>Python>>正文


Python sys.getdefaultencoding方法代碼示例

本文整理匯總了Python中sys.getdefaultencoding方法的典型用法代碼示例。如果您正苦於以下問題:Python sys.getdefaultencoding方法的具體用法?Python sys.getdefaultencoding怎麽用?Python sys.getdefaultencoding使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sys的用法示例。


在下文中一共展示了sys.getdefaultencoding方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: formatyearpage

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None):
        """
        Return a formatted year as a complete HTML page.
        """
        if encoding is None:
            encoding = sys.getdefaultencoding()
        v = []
        a = v.append
        a('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
        a('<html>\n')
        a('<head>\n')
        a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding)
        if css is not None:
            a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css)
        a('<title>Calendar for %d</title>\n' % theyear)
        a('</head>\n')
        a('<body>\n')
        a(self.formatyear(theyear, width))
        a('</body>\n')
        a('</html>\n')
        return ''.join(v).encode(encoding, "xmlcharrefreplace") 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:24,代碼來源:calendar.py

示例2: write

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def write(self, data, mode='w', ensure=False):
        """ write data into path.   If ensure is True create
        missing parent directories.
        """
        if ensure:
            self.dirpath().ensure(dir=1)
        if 'b' in mode:
            if not py.builtin._isbytes(data):
                raise ValueError("can only process bytes")
        else:
            if not py.builtin._istext(data):
                if not py.builtin._isbytes(data):
                    data = str(data)
                else:
                    data = py.builtin._totext(data, sys.getdefaultencoding())
        f = self.open(mode)
        try:
            f.write(data)
        finally:
            f.close() 
開發者ID:pytest-dev,項目名稱:py,代碼行數:22,代碼來源:local.py

示例3: sysexec

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def sysexec(self, *argv, **popen_opts):
        """ return stdout text from executing a system child process,
            where the 'self' path points to executable.
            The process is directly invoked and not through a system shell.
        """
        from subprocess import Popen, PIPE
        argv = map_as_list(str, argv)
        popen_opts['stdout'] = popen_opts['stderr'] = PIPE
        proc = Popen([str(self)] + argv, **popen_opts)
        stdout, stderr = proc.communicate()
        ret = proc.wait()
        if py.builtin._isbytes(stdout):
            stdout = py.builtin._totext(stdout, sys.getdefaultencoding())
        if ret != 0:
            if py.builtin._isbytes(stderr):
                stderr = py.builtin._totext(stderr, sys.getdefaultencoding())
            raise py.process.cmdexec.Error(ret, ret, str(self),
                                           stdout, stderr,)
        return stdout 
開發者ID:pytest-dev,項目名稱:py,代碼行數:21,代碼來源:local.py

示例4: cmdexec

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def cmdexec(cmd):
    """ return unicode output of executing 'cmd' in a separate process.

    raise cmdexec.Error exeception if the command failed.
    the exception will provide an 'err' attribute containing
    the error-output from the command.
    if the subprocess module does not provide a proper encoding/unicode strings
    sys.getdefaultencoding() will be used, if that does not exist, 'UTF-8'.
    """
    process = subprocess.Popen(cmd, shell=True,
            universal_newlines=True,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = process.communicate()
    if sys.version_info[0] < 3: # on py3 we get unicode strings, on py2 not
        try:
            default_encoding = sys.getdefaultencoding() # jython may not have it
        except AttributeError:
            default_encoding = sys.stdout.encoding or 'UTF-8'
        out = unicode(out, process.stdout.encoding or default_encoding)
        err = unicode(err, process.stderr.encoding or default_encoding)
    status = process.poll()
    if status:
        raise ExecutionFailed(status, status, cmd, out, err)
    return out 
開發者ID:pytest-dev,項目名稱:py,代碼行數:26,代碼來源:cmdexec.py

示例5: set_defaultencoding

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def set_defaultencoding(encoding):
    """
    Set default encoding (as given by sys.getdefaultencoding()) to the given
    encoding; restore on exit.

    Parameters
    ----------
    encoding : str
    """
    if not PY2:
        raise ValueError("set_defaultencoding context is only available "
                         "in Python 2.")
    orig = sys.getdefaultencoding()
    reload(sys)  # noqa:F821
    sys.setdefaultencoding(encoding)
    try:
        yield
    finally:
        sys.setdefaultencoding(orig)


# -----------------------------------------------------------------------------
# Console debugging tools 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:25,代碼來源:testing.py

示例6: _ustr

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def _ustr(obj):
        """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
           str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
           then < returns the unicode object | encodes it with the default encoding | ... >.
        """
        if isinstance(obj,unicode):
            return obj

        try:
            # If this works, then _ustr(obj) has the same behaviour as str(obj), so
            # it won't break any existing code.
            return str(obj)

        except UnicodeEncodeError:
            # Else encode it
            ret = unicode(obj).encode(sys.getdefaultencoding(), 'xmlcharrefreplace')
            xmlcharref = Regex('&#\d+;')
            xmlcharref.setParseAction(lambda t: '\\u' + hex(int(t[0][2:-1]))[2:])
            return xmlcharref.transformString(ret)

    # build list of single arg builtins, tolerant of Python version, that can be used as parse actions 
開發者ID:jpush,項目名稱:jbox,代碼行數:23,代碼來源:pyparsing.py

示例7: test_encoding

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def test_encoding(self):
        f = file(self.temp_file, 'w')
        # we throw on flush, CPython throws on write, so both write & close need to catch
        try:
            f.write(u'\u6211')
            f.close()
            self.fail('UnicodeEncodeError should have been thrown')
        except UnicodeEncodeError:
            pass
        
        if hasattr(sys, "setdefaultencoding"):
            #and verify UTF8 round trips correctly
            setenc = sys.setdefaultencoding
            saved = sys.getdefaultencoding()
            try:
                setenc('utf8')
                with file(self.temp_file, 'w') as f:
                    f.write(u'\u6211')

                with file(self.temp_file, 'r') as f:
                    txt = f.read()
                self.assertEqual(txt, u'\u6211')
            finally:
                setenc(saved) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:26,代碼來源:test_file.py

示例8: log

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def log(self, rev_start=None, rev_end=1, verbose=False):
        """ return a list of LogEntry instances for this path.
rev_start is the starting revision (defaulting to the first one).
rev_end is the last revision (defaulting to HEAD).
if verbose is True, then the LogEntry instances also know which files changed.
"""
        assert self.check()   # make it simpler for the pipe
        rev_start = rev_start is None and "HEAD" or rev_start
        rev_end = rev_end is None and "HEAD" or rev_end
        if rev_start == "HEAD" and rev_end == 1:
                rev_opt = ""
        else:
            rev_opt = "-r %s:%s" % (rev_start, rev_end)
        verbose_opt = verbose and "-v" or ""
        locale_env = fixlocale()
        # some blather on stderr
        auth_opt = self._makeauthoptions()
        #stdin, stdout, stderr  = os.popen3(locale_env +
        #                                   'svn log --xml %s %s %s "%s"' % (
        #                                    rev_opt, verbose_opt, auth_opt,
        #                                    self.strpath))
        cmd = locale_env + 'svn log --xml %s %s %s "%s"' % (
            rev_opt, verbose_opt, auth_opt, self.strpath)

        popen = subprocess.Popen(cmd,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    shell=True,
        )
        stdout, stderr = popen.communicate()
        stdout = py.builtin._totext(stdout, sys.getdefaultencoding())
        minidom,ExpatError = importxml()
        try:
            tree = minidom.parseString(stdout)
        except ExpatError:
            raise ValueError('no such revision')
        result = []
        for logentry in filter(None, tree.firstChild.childNodes):
            if logentry.nodeType == logentry.ELEMENT_NODE:
                result.append(LogEntry(logentry))
        return result 
開發者ID:pytest-dev,項目名稱:py,代碼行數:43,代碼來源:svnwc.py

示例9: test_read_write

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def test_read_write(self, tmpdir):
        x = tmpdir.join("hello")
        part = py.builtin._totext("hällo", "utf8")
        x.write(part)
        assert x.read() == part
        x.write(part.encode(sys.getdefaultencoding()))
        assert x.read() == part.encode(sys.getdefaultencoding()) 
開發者ID:pytest-dev,項目名稱:py,代碼行數:9,代碼來源:test_local.py

示例10: safe_decode

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def safe_decode(line, encoding, *args, **kwargs):
    '''return decoded line from encoding or decode with default encoding'''
    try:
        return line.decode(encoding or sys.getdefaultencoding(), *args, **kwargs)
    except LookupError:
        return line.decode(sys.getdefaultencoding(), *args, **kwargs) 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:8,代碼來源:utils.py

示例11: decoding_stream

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def decoding_stream(stream, encoding, errors='strict'):
    try:
        reader_cls = codecs.getreader(encoding or sys.getdefaultencoding())
    except LookupError:
        reader_cls = codecs.getreader(sys.getdefaultencoding())
    return reader_cls(stream, errors) 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:8,代碼來源:utils.py

示例12: encode

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def encode(self, string):
            if not isinstance(string, six.text_type):
                return string

            encoding = (getattr(self.out, 'encoding', None) or
                        locale.getpreferredencoding(do_setlocale=False) or
                        sys.getdefaultencoding())
            # errors=replace, we don't want to crash when attempting to show
            # source code line that can't be encoded with the current locale
            # settings
            return string.encode(encoding, 'replace') 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:13,代碼來源:__init__.py

示例13: format

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def format(self, record):
        if not hasattr(record, 'transfer_direction'):
            record.transfer_direction = ' '
        if not hasattr(record, 'log_name'):
            record.log_name = ""

        msg_lines = record.getMessage().splitlines(True)
        base_output = super(MultilineWithDirectionFormatter, self).format(record)
        out_lines = base_output.splitlines(True)
        output = out_lines[0]

        if len(msg_lines) >= 1:
            empty_prefix = self._calculate_empty_prefix(msg_lines[0], out_lines[0])
            for line in out_lines[1:]:
                try:
                    output += u"{}|{}".format(empty_prefix, line)
                except UnicodeDecodeError as err:
                    if hasattr(err, "encoding"):
                        encoding = err.encoding
                    else:
                        encoding = sys.getdefaultencoding()
                    decoded_line = codecs.decode(line, encoding, 'replace')
                    output += u"{}|{}".format(empty_prefix, decoded_line)

                    # TODO: line completion for connection decoded data comming in chunks
        output = MolerMainMultilineWithDirectionFormatter._remove_duplicate_log_name(record, output)
        return output 
開發者ID:nokia,項目名稱:moler,代碼行數:29,代碼來源:loggers.py

示例14: _ustr

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def _ustr(obj):
        """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
           str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
           then < returns the unicode object | encodes it with the default encoding | ... >.
        """
        if isinstance(obj,unicode):
            return obj

        try:
            # If this works, then _ustr(obj) has the same behaviour as str(obj), so
            # it won't break any existing code.
            return str(obj)

        except UnicodeEncodeError:
            # The Python docs (http://docs.python.org/ref/customization.html#l2h-182)
            # state that "The return value must be a string object". However, does a
            # unicode object (being a subclass of basestring) count as a "string
            # object"?
            # If so, then return a unicode object:
            return unicode(obj)
            # Else encode it... but how? There are many choices... :)
            # Replace unprintables with escape codes?
            #return unicode(obj).encode(sys.getdefaultencoding(), 'backslashreplace_errors')
            # Replace unprintables with question marks?
            #return unicode(obj).encode(sys.getdefaultencoding(), 'replace')
            # ...

    # build list of single arg builtins, tolerant of Python version, that can be used as parse actions 
開發者ID:vulscanteam,項目名稱:vulscan,代碼行數:30,代碼來源:pyparsing.py

示例15: to_bytes

# 需要導入模塊: import sys [as 別名]
# 或者: from sys import getdefaultencoding [as 別名]
def to_bytes(x, charset=sys.getdefaultencoding(), errors="strict"):
        if x is None:
            return None
        if isinstance(x, (bytes, bytearray, buffer)):
            return bytes(x)
        if isinstance(x, unicode):
            return x.encode(charset, errors)
        raise TypeError("Expected bytes") 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:10,代碼來源:_compat.py


注:本文中的sys.getdefaultencoding方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。