1 MySQL 的 utf-8
MySQL 數(shù)據(jù)庫的 utf-8 編碼數(shù)據(jù)讀取:MySQL 如果數(shù)據(jù)庫創(chuàng)建時(shí)使用了utf-8纯赎,存數(shù)據(jù)的時(shí)候是utf-8巡莹,那么在python讀數(shù)據(jù)庫,那么在也需要設(shè)定 utf-8 編碼抢韭。
推薦使用
import MySQLdb
db = MySQLdb.connect(...)
db.set_character_set('utf8')
cursor = db.cursor()
cursor.execute('SET NAMES utf8;')
或者參數(shù)上設(shè)定charset。參照 python,mysql,MySQLDb支持中文(utf-8編碼)
db = MySQLdb.connect(..., charset="utf8");
db = db.cursor();
db.execute("SET NAMES utf8");
或者兩個(gè)值都寫到參數(shù)中恍箭。參照 Writing UTF-8 String to MySQL with Python
conn = MySQLdb.connect(charset='utf8', init_command='SET NAMES UTF8')
對于 db.execute("SET NAMES utf8")
語句刻恭,以下三條效果是一樣的:
cursor.execute("SET NAMES utf8;")
cursor.execute("SET CHARACTER SET utf8;")
cursor.execute("SET character_set_connection=utf8;")
2 Python 自帶的 logging 模塊
logging 模塊的使用。以下代碼實(shí)現(xiàn)了:debug及以上級別日志寫入 my_app.log 文件中扯夭,同時(shí) info 級別及其以上級別的日志也輸出到終端鳍贾。
# coding:utf-8
import logging
logging_cfg = {'filename':'my_app.log'}
def init_logging():
logging.basicConfig(level=logging.DEBUG,
format='[%(asctime)s - %(levelname)-8s - %(filename)s - line: %(lineno)d] %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename=logging_cfg.get('filename', 'default_logging.log'),
filemode='a')
# 定義一個(gè)StreamHandler,將INFO級別或更高的日志信息打印到標(biāo)準(zhǔn)錯(cuò)誤交洗,并將其添加到當(dāng)前的日志處理對象
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s - %(name)s - %(levelname)-8s] %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
logging.info('logging module initialized, save as {}'.format(logging_cfg.get('filename', 'default_logging.log')))
init_logging()
logging.info('MAIN PROCEDURE BEGIN')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.info('MAIN PROCEDURE BEGIN')
logging 模塊可參考:
15.7. logging
— Logging facility for Python
3 Python 字符串占位符 %s
與 .format()
%s
是舊式占位符骑科,.format()
是新式占位符,更推薦使用构拳。
3.1 占位符對于位數(shù)的控制
我第一次看見看見 "%3d" %
這種操作時(shí)咆爽,以為是做“求余”的運(yùn)算,特別是對后面的隨機(jī)數(shù)求余置森,然而并不是斗埂。所以盡量使用 .format()
提高可讀性。
import random
print "%3d" % random.randint(1, 999)
print "{:0>3d}".format(random.randint(1, 999))
# 構(gòu)建齊整的位數(shù)
print "user_name" + "{:0>3d}".format(random.randint(1, 999))
print "%0.2f" % 99.12345
print "{:.2f}".format(+99.12345)
print "{:.2f}".format(-99.12345)
print "{:+.2f}".format(+99.12345)
print "{:+.2f}".format(-99.12345)
輸出結(jié)果
606
531
user_name234
99.12
99.12
-99.12
+99.12
-99.12
3.2 更多的 .format()
的好處
%s
一不注意就會(huì)寫成第一行注釋掉的代碼暇藏,導(dǎo)致報(bào)錯(cuò)蜜笤。對于多變量的占位符濒蒋,必須構(gòu)成元組盐碱。而且元組中的變量個(gè)數(shù)要和占位符數(shù)量相等。所以還是推薦 .format()
沪伙,可以用 {}
瓮顽,也可以指定元素所在位置 {1}
,或者可以使用變量代替围橡。
# print "Here are %s and %s" % "Li Lei", "Han Meimei" # 不寫括號來構(gòu)成元組暖混,Python 會(huì)報(bào)錯(cuò)
print "Here are %s and %s" % ("Li Lei", "Han Meimei")
# 類似于 %s 的用法
print "Here are {} and {}".format("Li Lei", "Han Meimei")
# 指定位數(shù)
print "Here are {1} and {0}. {0} is the first.".format("Li Lei", "Han Meimei")
print "Here are {1} and {2}".format("Li Lei", "Han Meimei", "Jim")
# 變量名代替
print "Here comes {person_1} and {person_2}".format(person_1="Li Lei", person_2="Han Meimei")
# 變量名代替,而且可以只是用一個(gè)變量
print "Here comes {person_1}.".format(person_1="Li Lei", person_2="Han Meimei")
4 兩種方式獲取當(dāng)前時(shí)間 datetime 與 time
重點(diǎn)是 datetime.datetim.now()
不是秒時(shí)間翁授,用 time.time()
得到的秒數(shù)拣播,int()
轉(zhuǎn)換之后晾咪,就可以兩個(gè)時(shí)間簡單相減獲得時(shí)間間隔,用來獲取某一段代碼耗時(shí)比較有用贮配。
?```python
In [1]: from datetime import datetime
In [1]: from datetime import datetime
In [2]: from time import time
In [3]: t = datetime.fromtimestamp(time())
In [4]: t
Out[4]: datetime.datetime(2017, 8, 3, 17, 23, 22, 6560)
In [5]: t.strftime("%H:%M:%S")
Out[5]: '17:23:22'
In [6]: t.strftime("%H:%M:%S:%f")
Out[6]: '17:23:22:006560'
In [7]: t.strftime("%H:%M:%S %f")
Out[7]: '17:23:22 006560'
In [8]: t.strftime("%H:%M:%S %fms")
Out[8]: '17:23:22 006560ms'
In [9]: datetime.now().strftime("%H:%M:%S %fms")
Out[9]: '17:25:15 110922ms'
5 文件頂部的語句會(huì)被執(zhí)行
假設(shè)同一目錄下谍倦,有兩個(gè)文件 a.py 和 b.py,如果想在 a.py 文件中引用了 b.py 文件中的 var_c 變量泪勒。
# a.py
from b import var_c
print var_c
結(jié)果發(fā)現(xiàn)昼蛀,引用的時(shí)候,會(huì)同時(shí)把 var_c = 123
以上的語句都執(zhí)行了圆存。
# b.py
print "hello"
def te():
print "where"
te()
var_c = 123
參考 寫在Python模塊頂層的代碼引起的一個(gè)Bug
6 另外的小 tips
6.1 Linux 查找進(jìn)程叼旋,并 kill 進(jìn)程
ps aux
是查看所有進(jìn)程,grep xxx
是查找對應(yīng)名稱沦辙,kill -9 XXX
是殺死 xxx 編號的進(jìn)程.
ps aux|grep python en.py
kill -9 xxx
6.2 python 函數(shù)可以使用函數(shù)外變量夫植,但是要改變變量,加 global
參考 python中在哪些情況下必須使用global來聲明全局變量油讯?
6.3 二進(jìn)制去除 '0b' 并補(bǔ)齊位數(shù)
zfill()
函數(shù)補(bǔ)齊至相應(yīng)位數(shù)偷崩。
- 對于 1 到 3 取數(shù)
- 對每個(gè)數(shù)求二進(jìn)制數(shù),用
bin()
方法撞羽,得到0b
開頭的二進(jìn)制數(shù) - 用
replace()
阐斜,去除0b
- 最后用
zfill(10)
填滿10位。
>>> for i in range(1, 3):
... print bin(i).replace("0b","").zfill(10)
...
0000000001
0000000010
0000000011