标签:乱码问题 passwd 数据转换 try 提高 pen bsp pre admin
1.mysql乱码问题:
#!/usr/bin/env python # _*_ encoding:utf-8 _*_ ‘‘‘ author: tiantiandas ‘‘‘ import sys reload(sys) sys.setdefaultencoding(‘gbk‘) import MySQLdb def Connect_Mysql(sql,host): db_info = {‘host‘: host, ‘user‘: ‘test‘, ‘db‘: ‘TestDB‘, ‘passwd‘: ‘dnstest‘, ‘charset‘:‘gbk‘} #很关键 try: connect = MySQLdb.connect(**db_info) cursor = connect.cursor() cursor.execute(sql) connect.commit() result = cursor.fetchone() return result except Exception as e: print e sys.exit(10) def main(): domain = sys.argv[1] query = ‘select Name,AdminDesc from EmailBox where Domain="{0}"‘.format(domain) try: Name, AdminDesc = Connect_Mysql(sql=query,host="host1") update = "update EmailBox set Name=‘{0}‘,AdminDesc=‘{1} where Domain=‘{2}‘".format(Name,AdminDesc) try: print update Connect_Mysql(sql=update,host=‘host2‘) except Exception as e: print e except Exception as e: print e if __name__ == ‘__main__‘: main()
2.关于编码和解码
#!/usr/bin/env python # _*_ encoding:utf-8 _*_ import chardet a="天天" print chardet.detect(a) 结果: {‘confidence‘: 0.75249999999999995, ‘encoding‘: ‘utf-8‘}
import urllib from chardet.universaldetector import UniversalDetector usock = urllib.urlopen(‘http://www.baidu.com/‘) #创建一个检测对象 detector = UniversalDetector() for line in usock.readlines(): #分块进行测试,直到达到阈值 detector.feed(line) if detector.done: break #关闭检测对象 detector.close() usock.close() #输出检测结果 print detector.result 运行结果: {‘confidence‘: 0.99, ‘encoding‘: ‘GB2312‘}
>>> name="天天" >>> name ‘\xe5\xa4\xa9\xe5\xa4\xa9‘ #天天 汉字的gbk码 >>> b=name.decode(‘gbk‘) >>> b u‘\u6fb6\u2541\u3049‘ >>> c=b.encode(‘utf8‘) >>> c ‘\xe6\xbe\xb6\xe2\x95\x81\xe3\x81\x89‘ —————————————————————————— >>> ‘\xcc\xec\xcc\xec‘.decode(‘gbk‘) u‘\u5929\u5929‘ >>> ‘\xcc\xec\xcc\xec‘.decode(‘gbk‘).encode(‘utf8‘) ‘\xe5\xa4\xa9\xe5\xa4\xa9‘ >>> ‘天天‘ ‘\xe5\xa4\xa9\xe5\xa4\xa9‘
标签:乱码问题 passwd 数据转换 try 提高 pen bsp pre admin
原文地址:http://www.cnblogs.com/tiantiandas/p/python-charset.html