当前位置: 首页>>代码示例>>Python>>正文


Python sys.setdefaultencoding方法代码示例

本文整理汇总了Python中sys.setdefaultencoding方法的典型用法代码示例。如果您正苦于以下问题:Python sys.setdefaultencoding方法的具体用法?Python sys.setdefaultencoding怎么用?Python sys.setdefaultencoding使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sys的用法示例。


在下文中一共展示了sys.setdefaultencoding方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: set_defaultencoding

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [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

示例2: setencoding

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [as 别名]
def setencoding():
    """Set the string encoding used by the Unicode implementation.  The
    default is 'ascii', but if you're willing to experiment, you can
    change this."""
    encoding = "ascii" # Default value set by _PyUnicode_Init()
    if 0:
        # Enable to support locale aware default string encodings.
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0:
        # Enable to switch off string to Unicode coercion and implicit
        # Unicode to string conversion.
        encoding = "undefined"
    if encoding != "ascii":
        # On Non-Unicode builds this will raise an AttributeError...
        sys.setdefaultencoding(encoding) # Needs Python Unicode build ! 
开发者ID:glmcdona,项目名称:meddle,代码行数:20,代码来源:site.py

示例3: main

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [as 别名]
def main():
    global ENABLE_USER_SITE

    abs__file__()
    known_paths = removeduppaths()
    if ENABLE_USER_SITE is None:
        ENABLE_USER_SITE = check_enableusersite()
    known_paths = addusersitepackages(known_paths)
    known_paths = addsitepackages(known_paths)
    if sys.platform == 'os2emx':
        setBEGINLIBPATH()
    setquit()
    setcopyright()
    sethelper()
    aliasmbcs()
    setencoding()
    execsitecustomize()
    if ENABLE_USER_SITE:
        execusercustomize()
    # Remove sys.setdefaultencoding() so that users cannot change the
    # encoding after initialization.  The test for presence is needed when
    # this module is run as a script, because this code is executed twice.
    if hasattr(sys, "setdefaultencoding"):
        del sys.setdefaultencoding 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:26,代码来源:site.py

示例4: test_encoding

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [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

示例5: export_users_xls

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [as 别名]
def export_users_xls(request):
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="FieldsightUsers.csv"'

    writer = csv.writer(response)

    writer.writerow(['First Name', 'Last Name', 'Username', 'Email', 'Organization'])
    users = User.objects.all()
    for u in users:
        org = u.user_roles.all().values('organization__name').distinct()
        org_list = []
        for i in org:
            org_list.append(i['organization__name'])

        writer.writerow([u.first_name, u.last_name, u.username, u.email, org_list])

    return response 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:23,代码来源:views.py

示例6: set_defaultencoding

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [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) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:21,代码来源:testing.py

示例7: handle

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [as 别名]
def handle(self, *args, **options):
        reload(sys)
        sys.setdefaultencoding('utf-8')

        spargs = utils.arglist_to_dict(options['spargs'])
        key = spargs.get('key', 'running')
        os.chdir(sys.path[0])

        red = redis.StrictRedis(host = config.redis_host, port = config.redis_part, db = config.redis_db,
                                password = config.redis_pass)
        res = red.get(key)
        if res != None:
            info = json.loads(res)
            info['name'] = 'clear_running'
            info['error_msg'] = 'interrupt error'
            red.lpush('retry_list', info)
            red.delete(key) 
开发者ID:awolfly9,项目名称:jd_analysis,代码行数:19,代码来源:clear_running.py

示例8: setUp

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [as 别名]
def setUp(self):
        """
        Add a log observer which records log events in C{self.out}.  Also,
        make sure the default string encoding is ASCII so that
        L{testSingleUnicode} can test the behavior of logging unencodable
        unicode messages.
        """
        self.out = FakeFile()
        self.lp = log.LogPublisher()
        self.flo = log.FileLogObserver(self.out)
        self.lp.addObserver(self.flo.emit)

        try:
            str(u'\N{VULGAR FRACTION ONE HALF}')
        except UnicodeEncodeError:
            # This is the behavior we want - don't change anything.
            self._origEncoding = None
        else:
            if _PY3:
                self._origEncoding = None
                return
            reload(sys)
            self._origEncoding = sys.getdefaultencoding()
            sys.setdefaultencoding('ascii') 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:26,代码来源:test_log.py

示例9: _begin_execute

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [as 别名]
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 
开发者ID:sotogarcia,项目名称:odoo-development,代码行数:18,代码来源:dev_code_tester.py

示例10: setencoding

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [as 别名]
def setencoding():
    """Set the string encoding used by the Unicode implementation.  The
    default is 'ascii', but if you're willing to experiment, you can
    change this."""
    encoding = "ascii"  # Default value set by _PyUnicode_Init()
    if 0:
        # Enable to support locale aware default string encodings.
        import locale

        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0:
        # Enable to switch off string to Unicode coercion and implicit
        # Unicode to string conversion.
        encoding = "undefined"
    if encoding != "ascii":
        # On Non-Unicode builds this will raise an AttributeError...
        sys.setdefaultencoding(encoding)  # Needs Python Unicode build ! 
开发者ID:QData,项目名称:deepWordBug,代码行数:21,代码来源:site.py

示例11: checkSystemEncoding

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [as 别名]
def checkSystemEncoding():
    """
    Checks for problematic encodings
    """

    if sys.getdefaultencoding() == "cp720":
        try:
            codecs.lookup("cp720")
        except LookupError:
            errMsg = "there is a known Python issue (#1616979) related "
            errMsg += "to support for charset 'cp720'. Please visit "
            errMsg += "'http://blog.oneortheother.info/tip/python-fix-cp720-encoding/index.html' "
            errMsg += "and follow the instructions to be able to fix it"
            logger.critical(errMsg)

            warnMsg = "temporary switching to charset 'cp1256'"
            logger.warn(warnMsg)

            reload(sys)
            sys.setdefaultencoding("cp1256") 
开发者ID:krintoxi,项目名称:NoobSec-Toolkit,代码行数:22,代码来源:common.py

示例12: set_default_encoding

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [as 别名]
def set_default_encoding():
    try:
        locale.setlocale(locale.LC_ALL, '')
    except:
        print ('WARNING: Failed to set default libc locale, using en_US.UTF-8')
        locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    try:
        enc = locale.getdefaultlocale()[1]
    except Exception:
        enc = None
    if not enc:
        enc = locale.nl_langinfo(locale.CODESET)
    if not enc or enc.lower() == 'ascii':
        enc = 'UTF-8'
    try:
        enc = codecs.lookup(enc).name
    except LookupError:
        enc = 'UTF-8'
    sys.setdefaultencoding(enc)
    del sys.setdefaultencoding 
开发者ID:kovidgoyal,项目名称:build-calibre,代码行数:22,代码来源:site.py

示例13: main

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [as 别名]
def main():
    sys.frozen = 'windows_exe'
    sys.setdefaultencoding('utf-8')
    aliasmbcs()

    sys.meta_path.insert(0, PydImporter())
    sys.path_importer_cache.clear()

    import linecache
    def fake_getline(filename, lineno, module_globals=None):
        return ''
    linecache.orig_getline = linecache.getline
    linecache.getline = fake_getline

    abs__file__()

    add_calibre_vars()

    # Needed for pywintypes to be able to load its DLL
    sys.path.append(os.path.join(sys.app_dir, 'app', 'DLLs'))

    return run_entry_point() 
开发者ID:kovidgoyal,项目名称:build-calibre,代码行数:24,代码来源:site.py

示例14: write_dimensions

# 需要导入模块: import sys [as 别名]
# 或者: from sys import setdefaultencoding [as 别名]
def write_dimensions(meta, data, path_mdd, path_ddf, text_key=None,
                     CRLF="CR", run=True, clean_up=True,
                     reuse_mdd=False):

    default_stdout = sys.stdout
    default_stderr = sys.stderr
    reload(sys)
    sys.setdefaultencoding("cp1252")
    sys.stdout = default_stdout
    sys.stderr = default_stderr

    out = dimensions_from_quantipy(
        meta, data, path_mdd, path_ddf, text_key, CRLF, run,
        clean_up, reuse_mdd
    )

    default_stdout = sys.stdout
    default_stderr = sys.stderr
    reload(sys)
    sys.setdefaultencoding("utf-8")
    sys.stdout = default_stdout
    sys.stderr = default_stderr
    return out 
开发者ID:Quantipy,项目名称:quantipy,代码行数:25,代码来源:io.py


注:本文中的sys.setdefaultencoding方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。