當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。