• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python sys.setdefaultencoding函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: main

def main():
    reload(sys)
    sys.setdefaultencoding('utf-8')
    
    # 创建文档对象
    document = Document('e:/docs/demo2.docx')
    
    # 读取文档中所有的段落列表
    ps = document.paragraphs
    # 每个段落有两个属性:style和text
    ps_detail = [(x.text,x.style.name) for x in ps]
    with open('out.tmp','w+') as fout:
        fout.write('')
    # 读取段落并写入一个文件
    with open('out.tmp','a+') as fout:
        for p in ps_detail:
            fout.write(p[0] + '\t' + p[1] + '\n\n')
    
    # 读取文档中的所有段落的列表
    tables = document.tables
    # 遍历table,并将所有单元格内容写入文件中
    with open('out.tmp','a+') as fout:
        for table in tables:
            for row in table.rows:
                for cell in row.cells:
                    fout.write(cell.text + '\t')
                fout.write('\n')
开发者ID:dnxbjyj,项目名称:python-basic,代码行数:27,代码来源:read_docx.py


示例17: get_movie_page

	def get_movie_page(self, response):
		reload(sys)
		sys.setdefaultencoding("utf-8")
		open('Pages/CrawledNextPages.log', 'ab').write(response.url + '\n')
		sel = Selector(response)
		next_pages = sel.xpath('//*[@class="pages"]/a/@href').extract()
		#if _DEBUG == True: 
		#		import pdb 
		#		pdb.set_trace() 
		#print next_pages
		item_pages = sel.xpath('//*[@class="folder"]/a/@href').extract()
		#open('Pages/Subpages.log', 'ab').write('\n'.join(next_pages))
		for next_page in next_pages:
		#	print self.get_complete_url(next_page)
		#	yield scrapy.http.Request(self.get_complete_url(next_page), callback=self.get_movie_page)
		#	if _DEBUG == True: 
		#		import pdb 
		#		pdb.set_trace() 
			open('Pages/NextPages.log', 'ab').write(response.url + '\n')
			yield self.make_requests_from_url(self.get_complete_url(next_page))
		for item_page in item_pages:
			item_page = self.get_complete_url(item_page)
			print item_page
			open('Pages/ItemPages.log', 'ab').write(item_page + '\n')
			yield scrapy.http.Request(item_page, callback=self.get_movie_item)
开发者ID:wangjun,项目名称:sexspider,代码行数:25,代码来源:spider.py


示例18: dotask

 def dotask(self):
     self.cmd = 'ping'
     if sys.platform == "win32":
         self.cmd += ' -n 3 '
     else:
         self.cmd += ' -c 3 '
     self.cmd += self.host
     # os.popen(self.cmd, 'r', self.result)
     print "default coding type: {0}".format(sys.getdefaultencoding())
     reload(sys)
     sys.setdefaultencoding('utf-8')
     args = shlex.split(self.cmd)
     p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     (tmpoutput, tmpouterr) = p.communicate()
     self.retcode = p.returncode
     self.output = "".join(tmpoutput)
     self.outerr = "".join(tmpouterr)
     print "return code: %d" % self.retcode
     print "stdout:"
     if self.output:
         if not isinstance(self.output, unicode):
             self.output = self.output.decode(chardet.detect(self.output)['encoding'])
         print self.output
     print "stderr:"
     if self.outerr:
         if not isinstance(self.outerr, unicode):
             self.outerr = self.outerr.decode(chardet.detect(self.outerr)['encoding'])
         print self.outerr
     '''
开发者ID:idealegg,项目名称:ping_lan_python,代码行数:29,代码来源:pingTask.py


示例19: main

def main( argv ):
    reload( sys )
    sys.setdefaultencoding( 'utf-8' )
    parser = optparse.OptionParser( usage = '''python collect.py start|stop|restart [-c config.xml]''' )
    parser.add_option( "-c", "--config", action = "store", type = "string", dest = "confFile" )
    parser.add_option( "-a", "--alllog", action = "store_true", dest = "alllog" )
    parser.add_option( "-n", "--notimestamp", action = "store_true", dest = "notimestamp" )
    parser.add_option( "-d", "--date", action = "store", type = "string", dest = "date" , default = 0, help = "specify the date(date or number). eg: 2013-1-21 ,  1 refer to yesterday " )
    ( options, args ) = parser.parse_args( sys.argv[1:] )
    # multi collect process under same path
    if options.confFile == None:
        confFile = 'config.xml'
    else:
        confFile = options.confFile
    if confFile.endswith( '.xml' ):
        pidFile = confFile[0:-4] + '.pid'
        logFile = '%s.log' % confFile[0:-4]
    else:
        pidFile = confFile + '.pid'
        logFile = '%s.log' % confFile
    # start or stop
    if len( args ) == 1 and args[0] in ['start', 'stop', 'restart']:
        collect = Collect( os.path.abspath( confFile ), os.path.abspath( pidFile ), os.path.abspath( logFile ), options.alllog, options.date, options.notimestamp )
        if args[0] == 'start':
            collect.start()
        elif args[0] == 'stop':
            collect.stop()
        else:
            collect.restart()
    else:
        parser.print_help()
        exit( -1 )
开发者ID:sleepyycat,项目名称:WebFramework,代码行数:32,代码来源:collect.py


示例20: __init__

    def __init__(self):
        reload(sys)
        sys.setdefaultencoding('UTF-8')
        self.data_type = 'main'
        # Title of the application
        self.title = '网易云音乐'
        # Main-menu list
        self.data_list = ['排行榜', '艺术家', '新碟上架', '精选歌单', '我的歌单', 'DJ节目', '打碟', '收藏', '搜索', '帮助']
        # Which page of the data_list is displayed (data_list may be displayed in multiple pages
        self.page_index = 0
        # The index of the current selected line
        self.current_line_index = 0
        self.present_songs = []
        self.player = Player()
        self.ui = Ui()
        self.netease = NetEase()
        self.screen = curses.initscr()
        self.screen.keypad(1)
        self.page_size = 10  # The number of lines that can be displayed on one page.
        self.stack = []
        self.dj_stack = []
        self.user_id = None
        self.user_name = None

        # Read in the collection and account in flavor.json
        try:
            config_file = file(Constant.conf_dir + "/flavor.json", 'r')
            data = json.loads(config_file.read())
            self.collection = data['collection']
            self.account = data['account']
            config_file.close()
        except:
            self.collection = []
            self.account = {}
开发者ID:manfred-exz,项目名称:musicbox,代码行数:34,代码来源:menu.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sys.setprofile函数代码示例发布时间:2022-05-27
下一篇:
Python sys.setcheckinterval函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap