当前位置: 首页>>代码示例>>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;未经允许,请勿转载。