Python淺談之總結(整理)
阿新 • • 發佈:2019-01-09
一、簡介
Python各方面的程式設計內容總結下來並不斷更新,以便以後使用時查詢。
二、詳解
1、Python獲取路徑檔名
(1)split()函式進行字串分割
(2)basename()函式
2、Python下的SQlite資料庫
Python2.5集成了pysqlite資料庫介面程式(sqlite3 模組),這是Python標準庫第一次將一個數據庫介面程式納入標準庫。SQLite操作的例子:
>>> import sqlite3 >>> cxn = sqlite3.connect('sqlite.db') >>> cur = cxn.cursor() >>> cur.execute('CREATE TABLE users(login VARCHAR(8), uid INTEGER)') <sqlite3.Cursor object at 0x7f176e186710> >>> cur.execute('INSERT INTO users VALUES("john", 100)') <sqlite3.Cursor object at 0x7f176e186710> >>> cur.execute('INSERT INTO users VALUES("jane", 110)') <sqlite3.Cursor object at 0x7f176e186710> >>> cur.execute('SELECT * FROM users') <sqlite3.Cursor object at 0x7f176e186710> >>> for eachUser in cur.fetchall(): ... print eachUser ... (u'john', 100) (u'jane', 110) >>> cur.execute('DROP TABLE users') <sqlite3.Cursor object at 0x7f176e186710> >>> cur.close() >>> cxn.commit() >>> cxn.close()
#!/usr/bin/env python import os from random import randrange as rrange COLSIZ = 10 DB_EXC = None def connect(dbDir, dbName): global DB_EXC try: import sqlite3 except ImportError, e: try: from pysqlite2 import dbapi2 as sqlite3 except ImportError, e: return None DB_EXC = sqlite3 if not os.path.isdir(dbDir): os.mkdir(dbDir) cxn = sqlite3.connect(os.path.join(dbDir, dbName)) return cxn def create(cur): try: cur.execute(''' CREATE TABLE users ( login VARCHAR(8), uid INTEGER, prid INTEGER) ''') except DB_EXC.OperationalError, e: drop(cur) create(cur) drop = lambda cur: cur.execute('DROP TABLE users') NAMES = ( ('aaron', 8312), ('angela', 7603), ('dave', 7306), ('davina',7902), ('elliot', 7911), ('ernie', 7410), ('jess', 7912), ('jim', 7512), ('larry', 7311), ('leslie', 7808), ('melissa', 8602), ('pat', 7711), ('serena', 7003), ('stan', 7607), ('faye', 6812), ('amy', 7209), ) def randName(): pick = list(NAMES) while len(pick) > 0: yield pick.pop(rrange(len(pick))) def insert(cur): cur.executemany("INSERT INTO users VALUES(?, ?, ?)", [(who, uid, rrange(1,5)) for who, uid in randName()]) getRC = lambda cur: cur.rowcount if hasattr(cur, 'rowcount') else -1 def update(cur): fr = rrange(1,5) to = rrange(1,5) cur.execute( "UPDATE users SET prid=%d WHERE prid=%d" % (to, fr)) return fr, to, getRC(cur) def delete(cur): rm = rrange(1,5) cur.execute('DELETE FROM users WHERE prid=%d' % rm) return rm, getRC(cur) def dbDump(cur): cur.execute('SELECT * FROM users') print '%s%s%s' % ('LOGIN'.ljust(COLSIZ), 'USERID'.ljust(COLSIZ), 'PROJ#'.ljust(COLSIZ)) for data in cur.fetchall(): print '%s%s%s' % tuple([str(s).title().ljust(COLSIZ) \ for s in data]) def main(): print '*** Connecting to sqlite database' cxn = connect('sqlitedir', 'test.db') if not cxn: print 'ERROR: %r not supported, exiting' % db return cur = cxn.cursor() print '*** Creating users table' create(cur) print '*** Inserting names into table' insert(cur) dbDump(cur) print '*** Randomly moving folks', fr, to, num = update(cur) print 'from one group (%d) to another (%d)' % (fr, to) print '\t(%d users moved)' % num dbDump(cur) print '*** Randomly choosing group', rm, num = delete(cur) print '(%d) to delete' % rm print '\t(%d users removed)' % num dbDump(cur) print '*** Dropping users table' drop(cur) cur.close() cxn.commit() cxn.close() if __name__ == '__main__': main()
3、print函式輸出
>>> str = 'hello world' >>> print str hello world >>> print 'length of (%s) is %d' %(str, len(str)) length of (hello world) is 11 >>> hex = 0xFF >>> print 'hex = %x, dec = %d, oct=%o' % (hex, hex, hex) hex = ff, dec = 255, oct=377 >>> import math >>> print 'pi = %10.3f' % math.pi pi = 3.142 >>> print 'pi = %-10.3f' % math.pi pi = 3.142 >>> print 'pi = %06d' % int(math.pi) pi = 000003 >>> precise = 4 >>> print ("%.*s" % (4,"python")) pyth >>> print ("%10.3s " % ("python")) pyt >>> lst = [1,2,3,4,'python'] >>> print lst [1, 2, 3, 4, 'python'] >>> for i in range(0,6): ... print i, ... 0 1 2 3 4 5 >>> import sys >>> sys.stdout.write('hello world\n') hello world
4、Python中文支援
新增一行宣告檔案編碼的註釋(python預設使用ASCII編碼),必須將編碼註釋放在第一行或者第二行。# -*- coding:utf-8 -*-
或者#coding=utf-8
Windows下使用:#coding=gbk
# -*- coding: gbk -*-
5、將python的py檔案編譯成保密的pyc檔案
由於python程式的py檔案很容易洩露原始碼,所以python可以編譯成保密的pyc檔案。python的pyc檔案是一種二進位制檔案,py檔案變成pyc檔案後,載入的速度有所提高,而且pyc是一種跨平臺的位元組碼,是由python的虛擬機器來執行的,這個是類似於JAVA或者.NET的虛擬機器的概念。
編pyc檔案也是可以反編譯的,不同版本編譯後的pyc檔案是不同的,根據python原始碼中提供的opcode,可以根據pyc檔案反編譯出py檔案原始碼,網上可以找到一個反編譯python2.3版本的pyc檔案的工具,不過該工具從python2.4開始就要收費了,如果需要反編譯出新版本的pyc檔案的話,就需要自己動手了,不過你可以自己修改python的原始碼中的opcode檔案,重新編譯python,從而防止不法分子的破解。
(1)編譯py檔案到pyc檔案的方法:在命令列輸入:python -m py_compile myFile.py 就可以生成對應的pyc檔案了(有時會將pyc的字尾改為py,通過file命令可以看出為byte-compiled)。
(2)內建的類庫來實現把py檔案編譯為pyc檔案,這個模組就是py_compile模組。
生成單個pyc檔案:
import py_compile
py_compile.compile(r'/tmp/test.py')
compile函式原型:compile(file[, cfile[, dfile[, doraise]]])file:表示需要編譯的py檔案的路徑
cfile:表示編譯後的pyc檔名稱和路徑,預設為直接在file檔名後加c 或者 o,o表示優化的位元組碼
dfile:這個引數英文看不明白,請各位大大賜教。(鄙視下自己)原文:it is used as the name of the source file in error messages instead of file
doraise:可以是兩個值,True或者False,如果為True,則會引發一個PyCompileError,否則如果編譯檔案出錯,則會有一個錯誤,預設顯示在sys.stderr中,而不會引發異常批量生成pyc檔案: 若工程都是在一個目錄下的,一般不會說僅僅編譯一個py檔案而已,而是需要把整個資料夾下的py檔案都編譯為pyc檔案,python又提供了另一個模組:compileall 。使用方法如下:
import compileall
compileall.compile_dir(r'/tmp/code/')
這樣就把/tmp/code目錄,以及其子目錄下的py檔案編譯為pyc檔案了。compile_dir函式的說明:compile_dir(dir[, maxlevels[, ddir[, force[, rx[, quiet]]]]])
dir:表示需要編譯的資料夾位置
maxlevels:表示需要遞迴編譯的子目錄的層數,預設是10層,即預設會把10層子目錄中的py檔案編譯為pyc
ddir:it is used as the base path from which the filenames used in error messages will be generated。
force:如果為True,則會強制編譯為pyc,即使現在的pyc檔案是最新的,還會強制編譯一次,pyc檔案中包含有時間戳,python編譯器會根據時間來決定,是否需要重新生成一次pyc檔案
rx:表示一個正則表示式,比如可以排除掉不想要的目錄,或者只有符合條件的目錄才進行編譯
quiet:如果為True,則編譯後,不會在標準輸出中,打印出資訊。
程式碼片段:
#-*- coding=utf-8
'''
#編譯目錄下所有py檔案為 pyc檔案
import compileall
compileall.compile_dir(r"/tmp/code/")
'''
#編譯 單個py檔案為 pyc檔案
import py_compile
py_compile.compile(r"/tmp/code/test.py")