Python
目錄
基本編程語法
Python腳本抬頭
使用Python作為腳本灭衷,需要輸入以下兩段文字
#!/usr/bin/python # 標(biāo)示該腳本使用Python執(zhí)行
# -*-coding:utf-8-*- # 標(biāo)示該腳本使用utf-8編碼
如果Python腳本在運行代碼是漂辐,出現(xiàn)編碼錯誤則加入以下代碼來解決
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
Python腳本接受參數(shù)
在腳本中加入以下代碼,即可接受腳本參數(shù)
import argparse
def __main__():
newParaser =argparse.ArgumentParser(description=description,usage=quick_usage)
newParaser.add_argument("-root_path", dest="root_path", help="所有根目錄树枫,也就是在哪個目錄下進(jìn)行搜索",default="***@bio.com")
newParaser.add_argument("-search_key", dest="search_key", help="用戶id螟加,將文件推送給對應(yīng)用戶", default="")
args = newParaser.parse_args()
argsDict = args.__dict__
root_path = argsDict.get('root_path')
search_key = argsDict.get('search_key')
if __name__ == "__main__":
__main__()
異常捕獲代碼
try:
x = 1000
except IoException as e:
throw e
except ValueError:
print 'error'
創(chuàng)建Python實體類
class Entity:
def __init__(self, param1, param2): # 構(gòu)造方法
self.param1 = param1
self.param2 = param2
def __str__(self): # str方法的打印語句
return "{param1:%s,param2:%s}" % (self.param1, str(self.param2))
def __repr__(self): # 內(nèi)嵌對象打印語句
return "{param1:%s,param2:%s}" % (self.param1, str(self.param2))
數(shù)據(jù)庫訪問
import MySQLdb
# 創(chuàng)建數(shù)據(jù)庫連接
connect = MySQLdb.connect(host=hostIp, user=userName, passwd=password, db=dbName)
# 查詢語句
cur = connect.cursor()
cur.execute(sql)
rows = cur.fetchall()
# update語句
cur = connect.cursor()
cur.execute(sql)
connect.commit()
執(zhí)行系統(tǒng)命令行
# 使用os模塊
import os
os.system(cmd)
# 或者使用
os.popen(cmd)
python使用枚舉對象
from enum import Enum
FileType = Enum('img', 'doc', 'xls')
python中的元類的理解
內(nèi)置方法
類常用內(nèi)置方法刀闷,具體的方法還請查考python魔法方法指南該魔法指南很詳細(xì)的介紹的python中每一種內(nèi)置方法的用法
__init__(self,...)
__del__(self)
__new__(cls,*args,**ked)
__str__(self)
__getitem__(self,key)
__len__(self)
__cmp__(stc,det)
模塊介紹
核心模塊介紹
__builtin__
exceptions
os
os.path
stat
string
re
math
cmath
operator
copy
sys
atexit
time
types
gc
標(biāo)準(zhǔn)模塊
fileinput
shutil
tempfile
StringIO
cStringIO
mmap
UserDist
UserList
UserString
traceback
errno
getopt
getpass
glob
fnmatch
random
whrandom
md5
sha
crypt
rotor
zlib
code
線程和進(jìn)程
threading
Queue
thread
commands
pipes
popen2
signal
數(shù)據(jù)標(biāo)示
array
struct
xdrlib
marshal
pickle
cPickle
copy_reg
pprint
repr
base64
binhex
quopri
uu
binascii
文件格式
xmllib
xml.parsers.expat
sgmllib
htmllib
htmlentitydefs
ConfigParser
netrc
shlex
zipfile
gzip
郵件和新聞消息處理
rfc822
mimetools
MimeWriter
mailbox
mailcap
mimetypes
packmail
mimify
multifile
網(wǎng)絡(luò)協(xié)議
socket
select
asyncore
asynchat
urlib
urlparser
cookie
rebotparser
ftplib
gopherlib
httplib
poplib
imaplib
smtplib
telnetlib
nntplib
SocketServer
BaseHTTPServer
SimpleHTTPServer
CGIHTTPServer
cgi
webbrower
國際化模塊
locale
unicodedata
ucnhash
更多模塊
更多模塊請參考 python 標(biāo)準(zhǔn)庫