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


Python sys.setdefaultencoding函数代码示例

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


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

示例1: get

    def get(self):
        # type = self.check_oper_right_custom_right(self._rightKey, self._exportUserKey)
        # if type == False:
        #     self.redirect(config.SOCRightConfig['siteDomain']+'Admin/NotRight')
        #     return

        import sys
        reload(sys)                        
        sys.setdefaultencoding('utf-8')    
        ps = self.get_page_config(title = '导出角色用户列表Excel')

        role = {}
        role['id'] = int(self.get_arg('id', '0'))
        role = role_logic.query_one(id = role['id'])
        ps['userName'] = self.get_arg('userName', '')        
        ps['page'] = int(self.get_arg('page', '1'))
        ps['pagedata'] = user_logic.query_page_by_roleid(roleID = role['id'], userName = ps['userName'], page = 1, size = 99999)

        users = ps['pagedata']['data']

        #生成excel文件
        info = u'''<table><tr><td>用户ID</td><td>用户名</td><td>姓名</td><td>部门名称</td><td>角色ID</td><td>角色名</td></tr>'''

        for user in users:
            u = u'''<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>''' % (str(user['id']), user['name'], user['realName'], 
                        user['departmentName'], role['id'], role['name'] )
            info = info + u
        info = info + u'</table>'
        fileName = config.SOCRightConfig['exportUserPath'] + str_helper.get_now_datestr() +'_'+ str_helper.get_uuid() + '.xls'

        path = config.SOCRightConfig['realPath'] + fileName
        file_object = open(path, 'w')
        file_object.write(info)
        file_object.close( )    
        self.redirect(config.SOCRightConfig['siteDomain']+fileName)
开发者ID:xssworm,项目名称:SOCRight,代码行数:35,代码来源:role_handler.py

示例2: _setEncoding

def _setEncoding():
	"""
	This definition sets the Application encoding.
	"""

	reload(sys)
	sys.setdefaultencoding("utf-8")
开发者ID:JulioCesarCampos,项目名称:sIBL_GUI,代码行数:7,代码来源:getSphinxDocumentationApi.py

示例3: test_astype_unicode

    def test_astype_unicode(self):

        # GH7758
        # a bit of magic is required to set default encoding encoding to utf-8
        digits = string.digits
        test_series = [
            Series([digits * 10,
                    tm.rands(63),
                    tm.rands(64),
                    tm.rands(1000)]),
            Series([u('データーサイエンス、お前はもう死んでいる')]),
        ]

        former_encoding = None
        if not compat.PY3:
            # in python we can force the default encoding for this test
            former_encoding = sys.getdefaultencoding()
            reload(sys)  # noqa
            sys.setdefaultencoding("utf-8")
        if sys.getdefaultencoding() == "utf-8":
            test_series.append(Series([u('野菜食べないとやばい').encode("utf-8")]))
        for s in test_series:
            res = s.astype("unicode")
            expec = s.map(compat.text_type)
            assert_series_equal(res, expec)
        # restore the former encoding
        if former_encoding is not None and former_encoding != "utf-8":
            reload(sys)  # noqa
            sys.setdefaultencoding(former_encoding)
开发者ID:ChunHungLiu,项目名称:pandas,代码行数:29,代码来源:test_dtypes.py

示例4: __init__

 def __init__(self):
     reload(sys)
     sys.setdefaultencoding("UTF-8")
     self.datatype = "main"
     self.title = "网易云音乐"
     self.datalist = ["排行榜", "艺术家", "新碟上架", "精选歌单", "我的歌单", "DJ节目", "打碟", "收藏", "搜索", "帮助"]
     self.offset = 0
     self.index = 0
     self.storage = Storage()
     self.storage.load()
     self.collection = self.storage.database["collections"][0]
     self.player = Player()
     self.ui = Ui()
     self.netease = NetEase()
     self.screen = curses.initscr()
     self.screen.keypad(1)
     self.step = 10
     self.stack = []
     self.djstack = []
     self.userid = None
     self.username = None
     self.resume_play = True
     signal.signal(signal.SIGWINCH, self.change_term)
     signal.signal(signal.SIGINT, self.send_kill)
     self.START = time.time()
开发者ID:garfieldjty,项目名称:musicbox,代码行数:25,代码来源:menu.py

示例5: getCurriculum

	def getCurriculum(self, index_read_text, xnd, xqd):
		print("执行获取课表的动作")
		postData = {
			'__EVENTTARGET': 'xnd',
			'__EVENTARGUMENT': '',
			'__VIEWSTATE' : index_read_text.xpath('//input[@name="__VIEWSTATE"]/@value')[0],
			'xnd' : xnd,
			'xqd' : xqd
		}
		secondRequest = requests.post(self.Curriculum_URL, data=postData, headers=self.header)
		#print(secondRequest.text)
		#这里的xpath表达式中 /text()  莫名其妙的就取到了所有该节点下的全部内容,
		#包括<br>标签分割的内容,经测试发现,text()函数跟在/后面可行,如果不跟,
		#则用item去取,例如 h.text 是不能取得全部内容的,原因不明,继续查官方文档
		#2015-12-12:text()只能取到上一级标签下的全部内容, br可以忽略掉取,但再加一层标签,无法取到内部。
		h_list = etree.HTML(secondRequest.text).xpath("//table[@id='Table1']//tr[position()>2]//td[@align]/text()")
		i = 0
		print('xnd = '+xnd+'   xqd = '+xqd)
		xnxqd = xnd+','+xqd

		import sys
		reload(sys)
		sys.setdefaultencoding( "utf-8" )
		l = []
		for h in range(len(h_list)):
			if h_list[h].decode('utf-8')[0:3] in [u'周一第', u'周二第', u'周三第', u'周四第', u'周五第', u'周六第',u'周日第']:
				l.append(h_list[h-1])
				l.append(h_list[h])
				l.append(h_list[h+1])
				l.append(h_list[h+2])
				h = h+3
				#print(str(i)+" : "+h)
		s = '!'.join(l)
		self.myCollection.update({'stuId':self.stuNum}, {"$set":{xnxqd:s}}, upsert=True)
		return etree.HTML(secondRequest.text)
开发者ID:EnvyLan,项目名称:CampusAssistantServer,代码行数:35,代码来源:GetJWXT.py

示例6: setDefaultEncoding

def setDefaultEncoding():
    if hasattr(sys, 'setdefaultencoding'):
        sys.setdefaultencoding(DEFAULT_ENCODING)
        del sys.setdefaultencoding
        import logging
        configLog = logging.getLogger('Config')
        configLog.info('Default encoding set to %s', sys.getdefaultencoding())
开发者ID:webiumsk,项目名称:WOT-0.9.12,代码行数:7,代码来源:bw_site.py

示例7: __init__

    def __init__(self,parent=None):  
        super(TestDialog,self).__init__(parent) 
        reload(sys)
        sys.setdefaultencoding('utf-8')
        #从网络获取最新数据
        gouke = gettheme_add.guoketheme('http://www.guokr.com/site/all','/site/all','http://www.guokr.com/site/all')
        gouke.getthemelist()
        document = getdocument.dodocument()
        document.inserthead2()
        
        
        self.pageid = 0
        self.query = False#是否点击查询按钮
        self.queryid = 0
        self.mainUi=myrssmain.Ui_MainWindow()
        self.mainUi.setupUi(self) 
        self.db = model.myrss()
        self.themecount = self.db.selectthemecount()[0]-1
        #初始化时间空间数据
        self.initaddtime = self.db.selectinittime()
        self.starttime = datetime.datetime.strptime(self.initaddtime[0][:10],'%Y-%m-%d')
        self.endtime = datetime.datetime.strptime(self.initaddtime[1][:10],'%Y-%m-%d')
#        print type(self.starttime)
        self.mainUi.starttime.setDate(self.starttime)
        self.mainUi.endtime.setDate(self.endtime)
        #加载数据
        self.loadtable()
        #界面操作
        self.mainUi.prepagebut.clicked.connect(self.prepage)
        self.mainUi.nextpagebut.clicked.connect(self.nextpage)
        self.mainUi.startpagebut.clicked.connect(self.startpage)
        self.mainUi.endpagebut.clicked.connect(self.endpage)
        self.mainUi.clearbut.clicked.connect(self.resetcont)
        self.mainUi.selectbut.clicked.connect(self.querycont)
开发者ID:testlins,项目名称:myrss,代码行数:34,代码来源:myrss.py

示例8: configure_locale

def configure_locale():
    logger.debug("Before %s", locale.nl_langinfo(locale.CODESET))
    current_locale = locale.getlocale()

    if current_locale[1] is None:
        logger.debug("No locale currently set. Attempting to get default locale.")
        default_locale = locale.getdefaultlocale()

        if default_locale[1] is None:
            logger.debug("No default locale exists. Let's try loading from /etc/default/locale")
            if os.path.exists("/etc/default/locale"):
                config = ConfigObj('/etc/default/locale')
                lang = config.get('LANG')
                new_locale = lang
            else:
                logger.error("/etc/default/locale could not be found! Please run 'sudo update-locale' from command-line.")
                sys.exit(1)
        else:
            new_locale = default_locale

        logger.info("New locale set to: %s", locale.setlocale(locale.LC_ALL, new_locale))



    reload(sys)
    sys.setdefaultencoding("UTF-8")
    current_locale_encoding = locale.getlocale()[1].lower()
    logger.debug("sys default encoding %s", sys.getdefaultencoding())
    logger.debug("After %s", locale.nl_langinfo(locale.CODESET))

    if current_locale_encoding not in ['utf-8', 'utf8']:
        logger.error("Need a UTF-8 locale. Currently '%s'. Exiting..." % current_locale_encoding)
        sys.exit(1)
开发者ID:AtomLaw,项目名称:Airtime,代码行数:33,代码来源:mm1.py

示例9: handle

 def handle(self, *args, **options):
     reload(sys)
     sys.setdefaultencoding('iso-8859-1')
     
     path = options.get('taxo_file')
     
     if path == None:
         raise CommandError('You need to provide the taxonomy file path --taxo-file or -f')
 
     f = open(path, 'rw')
     
     
     
     #first delete all nodes
     Node.objects.all().delete()
     
     taxonomy = pickle.load(f)
     
     msni = MySQLNodeImporter()
     for i in taxonomy:
         count = 0
         while count < 3 :
             try:
                 msni.importNode(taxonomy[i])
                 break
             except:
                 count += 1 
                 Command.logger.error('could not import :' . taxonomy[i])
         if count == 3 :
             Command.logger.warning('skipping node '  . taxonomy[i])
开发者ID:linares,项目名称:fwiki,代码行数:30,代码来源:mysqlimport.py

示例10: parse

 def parse(self,response):
     reload(sys)
     sys.setdefaultencoding('utf-8')
     for i in range(95000,99318):
         url = "https://www.dy2018.com/i/" + str(i) + ".html"
         print str(i) + '...open'
         yield scrapy.spiders.Request(url=url, callback=self.parse_do)
开发者ID:553672759,项目名称:xxgit,代码行数:7,代码来源:dianying.py

示例11: __init__

    def __init__(self, session):

        cmd.Cmd.__init__(self)

        self.session = session
        self.prompt = 'weevely> '

        # Load all available modules
        self._load_modules()

        # Load history file
        self._load_history()

        # Set a nice intro
        self.intro = template.Template(
            messages.terminal.welcome_to_s
        ).render(
            path = self.session.get('path'),
            conn_info = session.get_connection_info(),
            version = messages.version,
            default_shell = self.session.get('default_shell')
        )

        # Set default encoding utf8
        reload(sys)
        sys.setdefaultencoding('utf8')
开发者ID:Nicals,项目名称:weevely3,代码行数:26,代码来源:terminal.py

示例12: __enableDefaultEncoding

def __enableDefaultEncoding():
    import sys

    try:
        sys.setdefaultencoding("utf8")
    except LookupError:
        pass
开发者ID:webiapoky,项目名称:webiapoky,代码行数:7,代码来源:sitecustomize.py

示例13: __init__

    def __init__(self, irc):
        self.__parent = super(Mantis, self)
        self.__parent.__init__(irc)

        self.saidBugs = ircutils.IrcDict()
        sayTimeout = self.registryValue('bugSnarferTimeout')
        for k in irc.state.channels.keys():
            self.saidBugs[k] = TimeoutQueue(sayTimeout)

        self.urlbase = self.registryValue('urlbase')
        self.privateurlbase = self.registryValue('privateurlbase')

        if self.privateurlbase != "":
            serviceUrl = self.privateurlbase + '/api/soap/mantisconnect.php'
        else:
            serviceUrl = self.urlbase + '/api/soap/mantisconnect.php'

        self.server = SOAPProxy(serviceUrl)._ns(namespace)
        self.username = self.registryValue('username')
        self.password = self.registryValue('password')
        self.oldperiodic = self.registryValue('bugPeriodicCheck')
        self.irc = irc
        self.lastBug = 0

        bugPeriodicCheck = self.oldperiodic
        if bugPeriodicCheck > 0:
            schedule.addPeriodicEvent(self._bugPeriodicCheck, bugPeriodicCheck, name=self.name())

        reload(sys)
        sys.setdefaultencoding('utf-8')
开发者ID:dregad,项目名称:supybot-mantis,代码行数:30,代码来源:plugin.py

示例14: set_utf8_default_encoding

def set_utf8_default_encoding():
    if sys.getdefaultencoding() in ['utf-8', 'UTF-8','cp65001','CP65001']:
        return

    # Regenerate setdefaultencoding.
    reload(sys)
    sys.setdefaultencoding('utf-8')

    for attr in dir(locale):
        if attr[0:3] != 'LC_':
            continue
        aref = getattr(locale, attr)
        try:
            locale.setlocale(aref, '')
        except locale.Error:
            continue
        try:
            lang = locale.getlocale(aref)[0]
        except (TypeError, ValueError):
            continue
        if lang:
            try:
                locale.setlocale(aref, (lang, 'UTF-8'))
            except locale.Error:
                os.environ[attr] = lang + '.UTF-8'
    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error:
        pass
    return
开发者ID:fireinice,项目名称:yakindlestrip,代码行数:30,代码来源:kindlestrip.py

示例15: main

def main(argv):
	reload(sys);
	sys.setdefaultencoding('utf-8');
	
	#타겟 준비
	targets = argv[1:]
	
	#알림 메시지 초기화
	Notify.init("make_comic_book")
	title = u'그림책 만들기'
	
	if not targets:
		msg = u'대상을 선택해 주세요!'
		Notify.Notification.new(title, msg, '').show()
		sys.exit(1)
	
	#변환
	for target in targets:
		try:
			cbz = MakeCbz().make(target, u'.')
		except Exception, err:
			Notify.Notification.new(title, unicode(err), '').show()
			raise SystemExit()
			
		ufp.trashPut(target)
		
		#메시지 작성
		msg = u"<b>%(target)s</b>를 <b>%(cbz)s</b>로 묶었습니다." % locals()
		
		#알림 메시지 보이기
		Notify.Notification.new(title, msg, '').show()
开发者ID:Thestar3Preservation,项目名称:ScriptPack,代码行数:31,代码来源:그림책+만들기.py


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