sys.getdefaultencoding

Here are the examples of the python api sys.getdefaultencoding taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: babble
Source File: test_sys_jy.py
View license
    def test_resetmethod(self):
        gde = sys.getdefaultencoding
        sys.getdefaultencoding = 5
        self.assertEquals(sys.getdefaultencoding, 5)
        del sys.getdefaultencoding
        self.assertRaises(AttributeError, getattr, sys, 'getdefaultencoding')
        sys.getdefaultencoding = gde

Example 2

Project: medicare-demo
Source File: test_sys_jy.py
View license
    def test_resetmethod(self):
        gde = sys.getdefaultencoding
        sys.getdefaultencoding = 5
        self.assertEquals(sys.getdefaultencoding, 5)
        del sys.getdefaultencoding
        self.assertRaises(AttributeError, getattr, sys, 'getdefaultencoding')
        sys.getdefaultencoding = gde

Example 3

Project: imagrium
Source File: test_sys_jy.py
View license
    def test_resetmethod(self):
        gde = sys.getdefaultencoding
        sys.getdefaultencoding = 5
        self.assertEquals(sys.getdefaultencoding, 5)
        del sys.getdefaultencoding
        self.assertRaises(AttributeError, getattr, sys, 'getdefaultencoding')
        sys.getdefaultencoding = gde

Example 4

Project: vumi
Source File: vumi_codecs.py
View license
    def decode(self, byte_string, encoding=None, errors='strict'):
        if not isinstance(byte_string, str):
            raise VumiCodecException(
                'Only bytestrings accepted for decoding.')
        encoding = encoding or sys.getdefaultencoding()
        if encoding in self.custom_codecs:
            decoder = self.custom_codecs[encoding].decode
        else:
            decoder = codecs.getdecoder(encoding)
        obj, length = decoder(byte_string, errors)
        return obj

Example 5

Project: static3
Source File: static.py
View license
    def __init__(self, root, **kw):
        """Just set the root and any other attribs passes via **kw."""
        self.root = root
        self.encoding = sys.getdefaultencoding()

        for k, v in kw.items():
            setattr(self, k, v)

Example 6

Project: readtime
Source File: _compat.py
View license
    def u(text):
        if text is None:
            return None
        try:
            return text.decode('utf-8')
        except:
            try:
                return text.decode(sys.getdefaultencoding())
            except:
                try:
                    return unicode(text)
                except:
                    return text

Example 7

Project: nzbToMedia
Source File: torrent.py
View license
    def _get_name_string(self, codec=None):
        """Get the name"""
        if codec is None:
            codec = sys.getdefaultencoding()
        name = None
        # try to find name
        if 'name' in self._fields:
            name = self._fields['name'].value
        # if name is unicode, try to decode
        if isinstance(name, text_type):
            try:
                name = name.encode(codec)
            except UnicodeError:
                name = None
        return name

Example 8

Project: scikit-image
Source File: _build.py
View license
def process_tempita_pyx(fromfile):
    try:
        try:
            from Cython import Tempita as tempita
        except ImportError:
            import tempita
    except ImportError:
        raise Exception('Building requires Tempita: '
                        'pip install --user Tempita')
    template = tempita.Template.from_filename(fromfile,
                                              encoding=sys.getdefaultencoding())
    pyxcontent = template.substitute()
    if not fromfile.endswith('.pyx.in'):
        raise ValueError("Unexpected extension of %s." % fromfile)

    pyxfile = os.path.splitext(fromfile)[0]    # split off the .in ending
    with open(pyxfile, "w") as f:
        f.write(pyxcontent)

Example 9

Project: xbmc-addon-tvtumbler
Source File: torrent.py
View license
    def _get_name_string(self, codec=None):
        """Get the name"""
        if codec is None:
            codec = sys.getdefaultencoding()
        name = None
        # try to find name
        if 'name' in self._fields:
            name = self._fields['name'].value
        # if name is unicode, try to decode
        if isinstance(name, text_type):
            try:
                name = name.encode(codec)
            except UnicodeError:
                name = None
        return name

Example 10

Project: iris
Source File: test_cdm.py
View license
    @contextmanager
    def unicode_encoding_change(self, new_encoding):
        default_encoding = sys.getdefaultencoding()
        reload(sys).setdefaultencoding(new_encoding)
        yield
        sys.setdefaultencoding(default_encoding)
        del sys.setdefaultencoding

Example 11

Project: openmetadata
Source File: _compat.py
View license
def get_best_encoding(stream):
    """Returns the default stream encoding if not found."""
    rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()
    if is_ascii_encoding(rv):
        return 'utf-8'
    return rv

Example 12

Project: holland
Source File: multidict.py
View license
    def __init__(self, multi=None, encoding=None, errors='strict',
                 decode_keys=False):
        self.multi = multi
        if encoding is None:
            encoding = sys.getdefaultencoding()
        self.encoding = encoding
        self.errors = errors
        self.decode_keys = decode_keys

Example 13

Project: hitch
Source File: _compat.py
View license
def get_best_encoding(stream):
    """Returns the default stream encoding if not found."""
    rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()
    if is_ascii_encoding(rv):
        return 'utf-8'
    return rv

Example 14

Project: feedjack
Source File: feedjack_update.py
View license
def prints(tstr):
    """ lovely unicode
    """
    sys.stdout.write('%s\n' % (tstr.encode(sys.getdefaultencoding(),
                         'replace')))
    sys.stdout.flush()

Example 15

Project: ispyd
Source File: python.py
View license
    def do_defaultencoding(self, line):
        """defaultencoding
        Display the default encoding used when converting Unicode strings.
        This is the value available from 'sys.defaultencoding'."""

        print >> self.stdout, sys.getdefaultencoding()

Example 16

Project: diff-cover
Source File: git_path.py
View license
    @classmethod
    def set_cwd(cls, cwd):
        """
        Set the cwd that is used to manipulate paths.
        """
        if isinstance(cwd, six.binary_type):
            cwd = cwd.decode(sys.getdefaultencoding())
        cls._cwd = cwd
        cls._root = cls._git_root()

Example 17

Project: dask
Source File: csv.py
View license
@delayed
def _to_csv_chunk(df, **kwargs):
    import io
    if PY2:
        out = io.BytesIO()
    else:
        out = io.StringIO()
    df.to_csv(out, **kwargs)
    out.seek(0)
    if PY2:
        return out.getvalue()
    encoding = kwargs.get('encoding', sys.getdefaultencoding())
    return out.getvalue().encode(encoding)

Example 18

Project: scipy
Source File: cythonize.py
View license
def process_tempita_pyx(fromfile, tofile):
    try:
        try:
            from Cython import Tempita as tempita
        except ImportError:
            import tempita
    except ImportError:
        raise Exception('Building SciPy requires Tempita: '
                        'pip install --user Tempita')
    from_filename = tempita.Template.from_filename
    template = from_filename(fromfile, encoding=sys.getdefaultencoding())
    pyxcontent = template.substitute()
    assert fromfile.endswith('.pyx.in')
    pyxfile = fromfile[:-len('.pyx.in')] + '.pyx'
    with open(pyxfile, "w") as f:
        f.write(pyxcontent)
    process_pyx(pyxfile, tofile)

Example 19

Project: PyFunt
Source File: cythonize.py
View license
def process_tempita_pyx(fromfile, tofile):
    try:
        try:
            from Cython import Tempita as tempita
        except ImportError:
            import tempita
    except ImportError:
        raise Exception('Building PyFunt requires Tempita: '
                        'pip install --user Tempita')
    from_filename = tempita.Template.from_filename
    template = from_filename(fromfile, encoding=sys.getdefaultencoding())
    pyxcontent = template.substitute()
    assert fromfile.endswith('.pyx.in')
    pyxfile = fromfile[:-len('.pyx.in')] + '.pyx'
    with open(pyxfile, "w") as f:
        f.write(pyxcontent)
    process_pyx(pyxfile, tofile)

Example 20

Project: vim-wakatime
Source File: compat.py
View license
    def u(text):
        if text is None:
            return None
        try:
            return text.decode('utf-8')
        except:
            try:
                return text.decode(sys.getdefaultencoding())
            except:
                try:
                    return unicode(text)
                except:
                    return text.decode('utf-8', 'replace')

Example 21

Project: exetractor-clone
Source File: winmanifest.py
View license
    def parse(self, filename_or_file, initialize=True):
        """ Load manifest from file or file object """
        if isinstance(filename_or_file, (str, unicode)):
            filename = filename_or_file
        else:
            filename = filename_or_file.name
        try:
            domtree = minidom.parse(filename_or_file)
        except xml.parsers.expat.ExpatError, e:
            args = [e.args[0]]
            if isinstance(filename, unicode):
                filename = filename.encode(sys.getdefaultencoding(), "replace")
            args.insert(0, '\n  File "%s"\n   ' % filename)
            raise ManifestXMLParseError(" ".join([str(arg) for arg in args]))
        if initialize:
            self.__init__()
        self.filename = filename
        self.load_dom(domtree, False)

Example 22

Project: EE-Book
Source File: debug.py
View license
    @staticmethod
    def print_dict(data={}, key='', prefix=''):
        try:
            if isinstance(data, dict):
                for key in data:
                    Debug.print_dict(data[key], key, prefix + '   ')
            else:
                if isinstance(data, basestring):
                    print prefix + unicode(key) + ' => ' + data
                else:
                    print prefix + unicode(key) + ' => ' + unicode(data)
        except UnicodeEncodeError as error:
            Debug.logger.info(u'编码异常')
            Debug.logger.info(u'系统默认编码为:' + sys.getdefaultencoding())
            raise error
        return

Example 23

Project: pylint
Source File: spelling.py
View license
    def _check_docstring(self, node):
        """check the node has any spelling errors"""
        docstring = node.doc
        if not docstring:
            return

        start_line = node.lineno + 1
        if six.PY2:
            encoding = node.root().file_encoding
            docstring = docstring.decode(encoding or sys.getdefaultencoding(),
                                         'replace')

        # Go through lines of docstring
        for idx, line in enumerate(docstring.splitlines()):
            self._check_spelling('wrong-spelling-in-docstring',
                                 line, start_line + idx)

Example 24

Project: sublime-wakatime
Source File: WakaTime.py
View license
    def u(text):
        if text is None:
            return None
        if isinstance(text, bytes):
            try:
                return text.decode('utf-8')
            except:
                try:
                    return text.decode(sys.getdefaultencoding())
                except:
                    pass
        try:
            return str(text)
        except:
            return text.decode('utf-8', 'replace')

Example 25

Project: sublime-wakatime
Source File: WakaTime.py
View license
    def u(text):
        if text is None:
            return None
        try:
            return text.decode('utf-8')
        except:
            try:
                return text.decode(sys.getdefaultencoding())
            except:
                try:
                    return unicode(text)
                except:
                    return text.decode('utf-8', 'replace')

Example 26

Project: isso
Source File: wsgi.py
View license
    def __call__(self, environ, start_response):

        def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
            if x is None or isinstance(x, str):
                return x
            return x.decode(charset, errors)

        def fix_headers(status, headers, exc_info=None):
            headers = [(to_native(key), value) for key, value in headers]
            return start_response(status, headers, exc_info)

        return self.app(environ, fix_headers)

Example 27

Project: py12306
Source File: winmanifest.py
View license
    def parse(self, filename_or_file, initialize=True):
        """ Load manifest from file or file object """
        if isinstance(filename_or_file, (str, unicode)):
            filename = filename_or_file
        else:
            filename = filename_or_file.name
        try:
            domtree = minidom.parse(filename_or_file)
        except xml.parsers.expat.ExpatError, e:
            args = [e.args[0]]
            if isinstance(filename, unicode):
                filename = filename.encode(sys.getdefaultencoding(), "replace")
            args.insert(0, '\n  File "%s"\n   ' % filename)
            raise ManifestXMLParseError(" ".join([str(arg) for arg in args]))
        if initialize:
            self.__init__()
        self.filename = filename
        self.load_dom(domtree, False)

Example 28

Project: xunlei-lixian
Source File: diagnostics.py
View license
@command(name='diagnostics', usage='print helpful information for diagnostics')
def lx_diagnostics(args):
	'''
	usage: lx diagnostics
	'''
	from lixian_encoding import default_encoding
	print 'default_encoding ->', default_encoding
	import sys
	print 'sys.getdefaultencoding() ->', sys.getdefaultencoding()
	print 'sys.getfilesystemencoding() ->', sys.getfilesystemencoding()
	print r"print u'\u4e2d\u6587'.encode('utf-8') ->", u'\u4e2d\u6587'.encode('utf-8')
	print r"print u'\u4e2d\u6587'.encode('gbk') ->", u'\u4e2d\u6587'.encode('gbk')

Example 29

Project: web
Source File: fetch_blacklist.py
View license
    def printE(self, msg, newline=True):
        """Print to stderr. This expects unicode strings!"""
        encoding = self.stderr.encoding or sys.getdefaultencoding()
        self.stderr.write(msg.encode(encoding, 'replace'))
        if newline:
            self.stdout.write('\n')

Example 30

Project: gaphor
Source File: layout.py
View license
def serialize(layout):
    def _ser(widget, element):
        if isinstance(widget, SERIALIZABLE):
            sub = SubElement(element, type(widget).__name__.lower() , attributes(widget))
            widget.foreach(_ser, sub)
        else:
            sub = SubElement(element, 'widget', attributes(widget))

    tree = Element('layout')
    map(_ser, layout.frames, [tree] * len(layout.frames))

    return tostring(tree, encoding=sys.getdefaultencoding())

Example 31

Project: komodo-wakatime
Source File: compat.py
View license
    def u(text):
        if text is None:
            return None
        try:
            return text.decode('utf-8')
        except:
            try:
                return text.decode(sys.getdefaultencoding())
            except:
                try:
                    return unicode(text)
                except:
                    return text

Example 32

Project: pyexcel
Source File: sheet.py
View license
    def __repr__(self):
        if compact.PY2:
            default_encoding = sys.getdefaultencoding()
            if default_encoding == "ascii":
                result = self.texttable
                return result.encode('utf-8')

        return self.texttable

Example 33

Project: ssf
Source File: geocoders_old.py
View license
    @classmethod
    def _decode_page(cls, page):
        """Read the encoding (charset) of ``page`` and try to encode it using
        UTF-8."""
        contents = page.read()
        encoding = cls._get_encoding(page, contents) or sys.getdefaultencoding()
        return unicode(contents, encoding=encoding).encode('utf-8')

Example 34

Project: libearth
Source File: __init__.py
View license
def binary(string, var=None):
    """Makes ``string`` to :class:`str` in Python 2.
    Makes ``string`` to :class:`bytes` in Python 3 or IronPython.

    :param string: a string to cast it to :data:`binary_type`
    :type string: :class:`bytes`, :class:`str`, :class:`unicode`
    :param var: an optional variable name to be used for error message
    :type var: :class:`str`

    """
    if isinstance(string, text_type):
        if IRON_PYTHON:
            return bytes(string, sys.getdefaultencoding())
        return string.encode()
    elif isinstance(string, binary_type):
        return string
    if var:
        raise TypeError('{0} must be a string, not {1!r}'.format(var, string))
    raise TypeError('expected a string, not ' + repr(string))

Example 35

Project: wakatime-unity
Source File: compat.py
View license
    def u(text):
        if text is None:
            return None
        if isinstance(text, bytes):
            try:
                return text.decode('utf-8')
            except:
                try:
                    return text.decode(sys.getdefaultencoding())
                except:
                    pass
        try:
            return str(text)
        except:
            return text

Example 36

View license
    @classmethod
    def _decode_page(cls, page):
        """Read the encoding (charset) of ``page`` and try to encode it using
        UTF-8."""
        contents = page.read()
        encoding = cls._get_encoding(page, contents) or sys.getdefaultencoding()
        return unicode(contents, encoding=encoding).encode('utf-8')

Example 37

Project: pystache
Source File: test_renderer.py
View license
    def test_string_encoding__default(self):
        """
        Check the default value.

        """
        renderer = Renderer()
        self.assertEqual(renderer.string_encoding, sys.getdefaultencoding())

Example 38

Project: Transmission-XBMC
Source File: torrent.py
View license
    def _get_name_string(self, codec=None):
        """Get the name"""
        if codec is None:
            codec = sys.getdefaultencoding()
        name = None
        # try to find name
        if 'name' in self._fields:
            name = self._fields['name'].value
        # if name is unicode, try to decode
        if isinstance(name, text_type):
            try:
                name = name.encode(codec)
            except UnicodeError:
                name = None
        return name

Example 39

Project: vcstool
Source File: executor.py
View license
def output_result(result, hide_empty=False):
    output = result['output']
    if result['returncode'] == NotImplemented:
        output = ansi('yellowf') + output + ansi('reset')
    elif result['returncode']:
        if not output:
            output = 'Failed with return code %d' % result['returncode']
        output = ansi('redf') + output + ansi('reset')
    elif not result['cmd']:
        output = ansi('yellowf') + output + ansi('reset')
    if output or not hide_empty:
        client = result['client']
        print(ansi('bluef') + '=== ' + ansi('boldon') + client.path + ansi('boldoff') + ' (' + client.__class__.type + ') ===' + ansi('reset'))
    if output:
        try:
            print(output)
        except UnicodeEncodeError:
            print(output.encode(sys.getdefaultencoding(), 'replace'))

Example 40

Project: typefacet
Source File: test_renderer.py
View license
    def test_string_encoding__default(self):
        """
        Check the default value.

        """
        renderer = Renderer()
        self.assertEqual(renderer.string_encoding, sys.getdefaultencoding())

Example 41

Project: circuits
Source File: file.py
View license
    def init(self, filename, mode="r", bufsize=BUFSIZE, encoding=None,
             channel=channel):
        self._mode = mode
        self._bufsize = bufsize
        self._filename = filename
        self._encoding = encoding or getdefaultencoding()

        self._fd = None
        self._poller = None
        self._buffer = deque()
        self._closeflag = False

Example 42

Project: pyblish-base
Source File: _compat.py
View license
def get_best_encoding(stream):
    """Returns the default stream encoding if not found."""
    rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()
    if is_ascii_encoding(rv):
        return 'utf-8'
    return rv

Example 43

Project: KeenClient-Python
Source File: client.py
View license
    def generate_image_beacon(self, event_collection, event_body, timestamp=None):
        """ Generates an image beacon URL.

        :param event_collection: the name of the collection to insert the
        event to
        :param event_body: dict, the body of the event to insert the event to
        :param timestamp: datetime, optional, the timestamp of the event
        """
        event = Event(self.project_id, event_collection, event_body,
                      timestamp=timestamp)
        event_json = event.to_json()
        return "{0}/{1}/projects/{2}/events/{3}?api_key={4}&data={5}".format(
            self.api.base_url, self.api.api_version, self.project_id, self._url_escape(event_collection),
            self.api.write_key.decode(sys.getdefaultencoding()), self._base64_encode(event_json)
        )

Example 44

Project: wakatime
Source File: compat.py
View license
    def u(text):
        if text is None:
            return None
        try:
            return text.decode('utf-8')
        except:
            try:
                return text.decode(sys.getdefaultencoding())
            except:
                try:
                    return unicode(text)
                except:
                    return text.decode('utf-8', 'replace')

Example 45

Project: spitfire
Source File: i18n.py
View license
def macro_i18n(macro_node, arg_map, compiler):
    # fixme: parse the parameter list into something usable
    # macro_node.parameter_list

    # generate a fake translation for now to verify this is working
    # most apps will have to stub this part out somehow i think
    macro_content_ast = util.parse(macro_node.value, 'i18n_goal')
    i18n_msg = make_i18n_message(macro_node.value, macro_content_ast)
    i18n_msg_utf8 = i18n_msg.encode(sys.getdefaultencoding())
    #print "macro_content_ast"
    #print "orginal:", macro_node.value
    #print "i18n:", i18n_msg_utf8
    #visitor.print_tree(macro_content_ast)
    return i18n_msg

Example 46

Project: mishkal
Source File: multidict.py
View license
    def __init__(self, multi=None, encoding=None, errors='strict',
                 decode_keys=False):
        self.multi = multi
        if encoding is None:
            encoding = sys.getdefaultencoding()
        self.encoding = encoding
        self.errors = errors
        self.decode_keys = decode_keys

Example 47

Project: lino
Source File: __init__.py
View license
def unicode_string(x):
    """
    When we want unicode strings (e.g. translated exception messages)
    to appear in an Exception,
    we must first encode them using a non-strict errorhandler.
    Because the message of an Exception may not be a unicode string.

    """
    return str(x).encode(sys.getdefaultencoding(), 'backslashreplace')

Example 48

Project: pgi
Source File: test_misc.py
View license
    def test_module_dir(self):
        # make sure all descriptors show up in dir(module)
        self.assertTrue(len(dir(Gtk)) > 750)

        if _compat.PY2:
            self.assertEqual(sys.getdefaultencoding(), "ascii")
        else:
            self.assertEqual(sys.getdefaultencoding(), "utf-8")

        self.assertEqual(Gtk._version, "3.0")
        self.assertEqual(GObject._version, "2.0")
        self.assertEqual(GLib._version, "2.0")

Example 49

Project: sketch-wakatime
Source File: compat.py
View license
    def u(text):
        if text is None:
            return None
        try:
            return text.decode('utf-8')
        except:
            try:
                return text.decode(sys.getdefaultencoding())
            except:
                try:
                    return unicode(text)
                except:
                    return text.decode('utf-8', 'replace')

Example 50

Project: odoo-development
Source File: dev_code_tester.py
View license
    def _begin_execute(self):
        """ Switch encoding to UTF-8 and capture stdout to an StringIO object

            :return: current captured sys.stdout
        """

        new_stdout = StringIO()

        self._encoding = sys.getdefaultencoding()
        reload(sys)
        sys.setdefaultencoding('utf-8')

        self._stdout = sys.stdout
        sys.stdout = new_stdout

        return new_stdout