Python第十一天 異常處理 glob模塊和shlex模塊 打開外部程序和subprocess模塊 subprocess類 Pipe管道 operator模塊 sorted函數 os模塊 hashl

Python第十一天    異常處理  glob模塊和shlex模塊    打開外部程序和subprocess模塊  subprocess類  Pipe管道  operator模塊   sorted函數    os模塊   hashlib模塊  platform模塊  csv模塊

 

 

目錄html

Pycharm使用技巧(轉載)node

Python第一天  安裝  shell  文件python

Python次日  變量  運算符與表達式  input()與raw_input()區別  字符編碼  python轉義符  字符串格式化mysql

Python第三天 序列  5種數據類型  數值  字符串  列表  元組  字典git

Python第四天   流程控制   if else條件判斷   for循環 while循環程序員

Python第五天   文件訪問    for循環訪問文件    while循環訪問文件   字符串的startswith函數和split函數web

Python第六天   類型轉換正則表達式

Python第七天   函數  函數參數   函數變量   函數返回值  多類型傳值    冗餘參數   函數遞歸調用   匿名函數   內置函數   列表表達式/列表重寫算法

Python第八天  模塊   包   全局變量和內置變量__name__    Python pathsql

Python第九天  面向對象  類定義   類的屬性    類的方法    內部類   垃圾回收機制   類的繼承 裝飾器

Python第十天   print >> f,和fd.write()的區別    stdout的buffer  標準輸入 標準輸出  標準錯誤   重定向 輸出流和輸入流

Python第十一天    異常處理  glob模塊和shlex模塊    打開外部程序和subprocess模塊  subprocess類  Pipe管道  operator模塊   sorted函數   生成器  walk模塊   hashlib模塊

Python第十二天     收集主機信息     正則表達式  無名分組   有名分組

Python第十三天   django 1.6   導入模板   定義數據模型   訪問數據庫   GET和POST方法    SimpleCMDB項目   urllib模塊   urllib2模塊  httplib模塊  django和web服務器整合  wsgi模塊   gunicorn模塊

Python第十四天 序列化  pickle模塊  cPickle模塊  JSON模塊  API的兩種格式

Python第十五天  datetime模塊 time模塊   thread模塊  threading模塊  Queue隊列模塊  multiprocessing模塊  paramiko模塊  fabric模塊  

 


python標準庫,python自帶的模塊
不是python標準庫,不是python自帶的模塊都須要安裝第三方軟件

 

 

 

hashlib模塊
至關於shell裏面的md5sum命令
必定要去除換行符

不能對目錄進行求md5值,變通一下,對目錄下的全部文件求md5值就是目錄的md5值

import hashlib
md5 = hashlib.md5()
md5.update('hello')
md5.hexdigest()
'5d41402abc4b2a76b9719d911017c592'

 

hashlib.md5(lines).hexdigest()


等價於 echo -n hello |md5sum  #echo必定要加 -n,否則md5sum會把換行符也算進去
5d41402abc4b2a76b9719d911017c592

 

 

md5.update方法會追加後來添加的值
md5.update('a')
md5.update('b')
#計算出來的是ab的md5值,也就是md5.update('ab')
md5.hexdigest()

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__="huazai"
"""
md5加密一個文件
Date:2016.08.12
"""




import sys
import hashlib

def md5sum(f):
    m = hashlib.md5()
    with open(f) as fd:
        while True:
            data = fd.read(4096)
            if data:
                m.update(data)
            else:
                break
    return m.hexdigest()

if __name__ == '__main__':
    try:
        print md5sum(sys.argv[1])
    except IndexError:
        print "%s follow a argument" % __file__

 

hashlib.md5 只是一個生成hash對象的hash函數
openssl_md5(...)
Returns a md5 hash object; optionally initialized with a string

print hashlib.md5
<built-in function openssl_md5>

####################
hashlib.md5() 返回一個hash對象
class HASH(__builtin__.object)
| A hash represents the object used to calculate a checksum of a
| string of information.
|
| Methods: 方法
|
| update() -- updates the current digest with an additional string 更新md5對象的原有內容 再加上本次加的內容
md5.update('a')
md5.update('b')
#計算出來的是ab的md5值,也就是md5.update('ab')
| digest() -- return the current digest value 返回md5對象的內容
| hexdigest() -- return the current digest as a string of hexadecimal digits 返回md5對象加密後的內容
| copy() -- return a copy of the current hash object 返回md5對象的拷貝
|
| Attributes: 屬性
|
| name -- the hash algorithm being used by this object, hash算法名字通常返回md5
| digest_size -- number of bytes in this hashes output
print hashlib.md5()
<md5 HASH object @ 000000000220DA30>

 

 


 

os模塊

目錄和路徑方法

 

#得到當前路徑
import os
print(os.getcwd())


#當前目錄切換到D:\test目錄下
os.chdir(r'D:\QMDownload')
print(os.getcwd())


#列出當前目錄的文件和文件夾
print(os.listdir(os.getcwd()))


#在當前目錄下建立abc目錄
os.mkdir('abc')


#刪除當前目錄下的1.txt文件,若是文件不存在會報錯
os.remove('1.txt')


#打印操做系統的分隔符,Linux爲\n ,windows爲\r\n
print(os.linesep)


#路徑拼接
print(os.path.join(os.getcwd(),'abc.txt'))


#分割文件名和目錄
print(os.path.split('D:\test\1.txt'))


#把驅動器號和後面路徑分割
print(os.path.splitdrive(os.getcwd()))


#把文件路徑和文件的後綴名分割
print(os.path.splitext('D:\test\1.txt'))


#獲取當前用戶的家目錄
print(os.path.expanduser('~/.bashrc'))

 

os.path

拆分路徑
split :返回一個二元組,包含文件的路徑與文件名
dirname :返回文件的路徑
basename :返回文件的文件名
splitext :返回一個除去文件擴展名的部分和擴展名的二元組

構建路徑
expanduser :展開用戶的HOME 目錄,如~、~username
abspath :獲得文件或路徑的絕對路徑
realpath :返回path的真實路徑,若是是軟連接返回軟連接的源文件
join :根據不一樣的操做系統平臺,使用不一樣的路徑分隔符拼接路徑

獲取文件屬性
getatime : 獲取文件的訪問時間;
getmtime : 獲取文件的修改時間;
getctime : 獲取文件的建立時間;
getsize : 獲取文件的大小

判斷文件類型
isabs('.'): 參數path 所指向的路徑存在,而且是一個絕對路徑
exists : 參數path 所指向的路徑是否存在;
isfile : 參數path 所指向的路徑存在,而且是一個文件;
isdir : 參數path 所指向的路徑存在,而且是一個文件夾;
islink : 參數path 所指向的路徑存在,而且是一個連接;
ismount : 參數path 所指向的路徑存在,而且是一個掛載點。

 

文件操做
getcwd : 返回當前工做路徑
chdir :重定向當前工做路徑
unlink/remove :刪除path 路徑所指向的文件;
rmdir :刪除path 路徑鎖指向的文件夾,該文件夾必須爲空, 不然會報錯;
mkdir :建立一個文件夾;
rename : 重命名文件或文件夾。

 

os.walk 

迭代目錄裏文件
os.walk返回的是1個元組(生成器對象),walk()函數裏用了yield關鍵字, 生成目錄樹,這個元組有3個元素,分別是dirpath, dirnames, filenames,因此使用3個變量p,d,f去接收這3個元素,即for p,d,f in a
filenames是個列表,對應的是f,因此對f進行for循環遍歷,取裏面的每個文件名,最後把文件名組織成帶路徑的,即os.path.join(p,i)。

 

例如

ll -R /tmp/mysql/
/tmp/mysql/:
total 12
-rw-r--r-- 1 root root    7 Sep 17 10:04 22.txt
drwxr-xr-x 3 root root 4096 Sep 17 11:15 3dir
-rw-r--r-- 1 root root    5 Sep 17 11:15 88.txt

/tmp/mysql/3dir:
total 8
drwxr-xr-x 2 root root 4096 Sep 17 11:24 2dir
-rw-r--r-- 1 root root    4 Sep 17 11:08 33.txt

/tmp/mysql/3dir/2dir:
total 4
-rw-r--r-- 1 root root 4 Sep 17 11:24 55.txt



roo = os.walk("/tmp/mysql")
for p, d, f in roo:
    print p,d,f   
/tmp/mysql ['3dir'] ['88.txt', '22.txt']
/tmp/mysql/3dir ['2dir'] ['33.txt']
/tmp/mysql/3dir/2dir [] ['55.txt']
dirpath, dirnames, filenames
若是目錄下面沒有目錄則dirnames爲空

 

示例
def 遞歸打印指定目錄下的目錄和文件(topdir):
    roo = os.walk(topdir)
    for p, d, f in roo:
        for i in f:
            print os.path.join(p,i)
        for j in d:
            print os.path.join(p,j)
            

 

 

示例
#!/usr/bin/env python

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__="huazai"
"""
實現功能:find  . -type f  -exec md5sum {} \;
Date:2016.08.12
"""





import os
import sys
import hashlib

def md5sum(f):
   m = hashlib.md5()
   with open(f) as fd:
       while True:
           data = fd.read(4096)
           if data:
               m.update(data)
           else:
               break
               return m.hexdigest()

def file_md5(topdir):
    a = os.walk(topdir)
    for p, d, f in a:
        for i in f:
            fn = os.path.join(p,i)
            md5 = md5sum(fn)
            yield "%s %s" % (md5, fn)  # 每調用一次,返回一個文件和該文件的md5值,固然也能夠把文件和md5值保存在字典裏,讀取字典裏的key和value

if __name__ == '__main__':
    lines = ''
try:
    topdir = sys.argv[1]
except IndexError:
    print "%s follow a dir" % __file__
    sys.exit()

gen = file_md5(topdir)  #gen是一個生成器對象

for i in gen:
    lines += i+'\n'
print lines
print hashlib.md5(lines).hexdigest()

 

os.walk作不了遞歸,用listdir來作

def list_all_files(rootdir):
    files = []
    list = os.listdir(rootdir) #列出文件夾下全部的目錄與文件
    for i in range(0,len(list)):
           path = os.path.join(rootdir,list[i])
           if os.path.isdir(path) and path.find('.idea') == -1 and path.find('.svn') == -1:
               files.extend(list_all_files(path))
           if os.path.isfile(path):
               name, ext = os.path.splitext(path)
               if ext == '.py' and name != '__init__':
                   files.append(path)

    return files


fs = list_all_files(pro_path)

for file in fs:
    __import__(file)

 


os.environ
環境變量
設置系統環境變量
一、os.environ['環境變量名稱']='環境變量值' #其中key和value均爲string類型
二、os.putenv('環境變量名稱', '環境變量值')

 

獲取系統環境變量
一、os.environ['環境變量名稱']
二、os.getenv('環境變量名稱')

Linux經常使用環境變量
os.environ['USER']:當前使用用戶。
os.environ['LC_COLLATE']:路徑擴展的結果排序時的字母順序。
os.environ['SHELL']:使用shell的類型。
os.environ['LAN']:使用的語言。
os.environ['SSH_AUTH_SOCK']:ssh的執行路徑
os.environ['TZ'] :使用的時區

 

 

 



operator模塊
sorted函數

按字典值排序


sorted函數
第一個參數是必須的,必須傳入一個可迭代對象用來排序,其餘參數都有默認值
reverse表示正向仍是反向排序,默認是false便是正向
key表示排序的值,若是是字典經過operator來選擇key排序仍是value排序
返回值是一個列表,跟字典轉列表同樣

dic={1:1,2:2,3:3}
print dic.items()
[(1, 1), (2, 2), (3, 3)]


sorted(可迭代對象,cmp,key,reverse)

operator.itemgetter(0):按照key來排序
operator.itemgetter(1):按照value來排序

按照字典value排序,相似sort -k命令
import operator
x = {1:2, 3:4, 4:3, 2:1, 0:0}
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
sorted_y = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)



找出佔用空間大的文件
os.walk
os.path.getsize
dict sort (top10)
#!/usr/bin/env python

import os
import sys
import operator

def gen_dic(topdir):
    dic = {}
    a = os.walk(topdir)
    for p, d, f in a:
        for i in f:
            fn = os.path.join(p, i)
            f_size = os.path.getsize(fn)
            dic[fn] = f_size
    return dic

if __name__ == '__main__':
    dic = gen_dic(sys.argv[1])
    sorted_dic = sorted(dic.iteritems(), key=operator.itemgetter(1), reverse=True)
    for k, v in sorted_dic[:10]:
        print k, '-->', v

 

 


 

打開外部程序和subprocess模塊  subprocess類  Pipe管道

os.system:輸出在終端上,捕獲不到
os.popen:只能捕捉到標準輸出,捕捉不到標準錯誤輸出
os.popen2:返回2個對象,一個是標準輸入,一個標準輸出
os.popen3:返回3個對象,標準輸入,標準輸出,標準錯誤輸出
os.popen4:已經廢棄,不建議使用,用subprocess模塊代替,返回2個對象,pipe_in和pipe_out_err

os.popenX都不建議使用,使用subprocess模塊代替os.popenX


示例

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__="huazai"
"""
實現功能:find  . -type f  -exec md5sum {} \;
Date:2016.08.12
"""import os

s = os.system('ls')
print s # 只能看到命令成功與否的返回值,不能保存命令執行結果

pipe_out = os.popen('ls')
pipe_out.read() # 讀取命令的執行結果

(pipe_in, pipe_out) = os.popen2('sort')
pipe_in.write('z\n')
pipe_in.write('a\n')
pipe_in.close() # 關閉管道 關閉文件
pipe_out.read()

pipe_in, pipe_out, pipe_err = os.popen3('sort')
pipe_err.read()

pipe_in, pipe_out_err = os.popen4('sort')

 


subprocess模塊

替代下面模塊和函數
os.system
os.spawn*
os.popen*
popen2.*
commands.*


import subprocess
subprocess.call(['ls', '-l','--color','/root'])  ,call(*popenargs, **kwargs) call函數默認接收多個參數,元組和字典
subprocess.call('ls -l --color /root', shell=True) # shell=True表示命令在shell下執行,默認狀況shell=False,參數是列表狀況下,shell=True,因此不用顯式聲明shell=True

注意:windows默認是 shell =False
subprocess.call(['ls','-l', '--color', '/root']) 等價於subprocess.call('ls -l --color /root', shell=True)

輸出不能捕捉到,與os.system同樣
subprocess.check_call(['mkdir', '/tmp/aaa'])
check_call會拋python異常

call和check_call跟os.popenX不同,不須要調用wait方法,父進程會默認等待子進程執行完才返回

 https://stackoverflow.com/questions/2837214/python-popen-command-wait-until-the-command-is-finished

 

 

subprocess類

http://www.cnblogs.com/zhoug2020/p/5079407.html

原型
subprocess.Popen(self, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)



args:
args參數。能夠是一個字符串,能夠是一個包含程序參數的列表。要執行的程序通常就是這個列表的第一項,或者是字符串自己。
subprocess.Popen(["cat","test.txt"])
subprocess.Popen("cat test.txt")
這兩個之中,後者將不會工做。由於若是是一個字符串的話,必須是程序的路徑才能夠。(考慮unix的api函數exec,接受的是字符串
列表)
可是下面的能夠工做
subprocess.Popen("cat test.txt", shell=True)
這是由於它至關於
subprocess.Popen(["/bin/sh", "-c", "cat test.txt"])
在*nix下,當shell=False(默認)時,Popen使用os.execvp()來執行子程序。args通常要是一個【列表】。若是args是個字符串的
話,會被當作是可執行文件的路徑,這樣就不能傳入任何參數了。

注意:
shlex.split()能夠被用於序列化複雜的命令參數,好比:
>>> shlex.split('ls ps top grep pkill')
['ls', 'ps', 'top', 'grep', 'pkill']
>>>import shlex, subprocess
>>>command_line = raw_input()
/bin/cat -input test.txt -output "diege.txt" -cmd "echo '$MONEY'"
>>>args = shlex.split(command_line)
>>> print args
['/bin/cat', '-input', 'test.txt', '-output', 'diege.txt', '-cmd', "echo '$MONEY'"]
>>>p=subprocess.Popen(args)
能夠看到,空格分隔的選項(如-input)和參數(如test.txt)會被分割爲列表裏獨立的項,但引號裏的或者轉義過的空格不在此列
。這也有點像大多數shell的行爲。

在*nix下,當shell=True時,若是arg是個字符串,就使用shell來解釋執行這個字符串。若是args是個列表,則列表第一個元素被視爲命令,
其他的都視爲是給shell自己的參數。也就是說,等效於:
subprocess.Popen(['/bin/sh', '-c', args[0], args[1], ...])


executable參數:
指定要執行的程序。它不多會被用到:通常程序能夠由args 參數指定。若是shell=True ,executable
能夠用於指定用哪一個shell來執行(好比bash、csh、zsh等)。*nix下,默認是 /bin/sh ,

注意:args自己是列表的狀況下,就不能加shell=True ,不然會執行失敗:Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE,shell=True) !!!

加了shell=True,命令不能是列表
不加shell=True時,命令是列表
shell=True,表示使用shell的命令方式執行命令,shell下的命令就是字符串

subprocess.Popen(['mkdir', 'aaa'],stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

 

在*nix下,當shell=True時,若是arg是個字符串,就使用shell來解釋執行這個字符串。若是args是個列表,則第一項被視爲命令,
其他的都視爲是給shell自己的參數。也就是說,等效於:
subprocess.Popen(['/bin/sh', '-c', args[0], args[1], ...])

注意:當調用mysqldump 這種命令時候,他會把> %s  也會當成命令的參數,因此不能用shlex.split(cmd)
cmd = "/usr/local/mysql/bin/mysqldump  -u%s -p%s  -P%s  -h%s   --all-databases > %s " % (mysqluser,mysqlpwd,mysqlport,mysqlhost,sqlfile)
p = Popen(shlex.split(cmd), stdout=PIPE,stderr=PIPE)

 



注意:windows默認是 shell =False!!!
爲什麼叫subprocess,調用外部命令的時候其實是fork出一個子進程子shell來執行

p=subprocess.Popen(['cat'],stdin=subprocess.PIPE,stdout=subprocess.PIPE) 要從標準輸入輸入數據就必須指定stdin=subprocess.PIPE

p=subprocess.Popen(['mkdir', 'aaa'],stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

p = Popen(['wc'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.terminate() #終止子進程
p.pid #子進程的pid
p.returncode #子進程執行完的返回碼,若是爲None,表示子進程還沒終止,若是爲負數-N的話,表示子進程還沒正常執行完畢而被N號信號終止,若是爲0表示子進程已經正常執行完畢
p.poll() #檢查子進程狀態
p.kill() #給子進程發送sigkill信號終止子進程
p.send_signal() #向子進程發送信號




Popen.wait()和Popen.communicate(input=None)都是等待子進程/程序運行結束並獲取返回值p.returncode
可是若是不須要等待子進程/程序運行結束,好比調用某些服務程序,例如vsftpd,mysql,這些服務一旦啓動就不須要等待他結束就不要用Popen.wait()和Popen.communicate(input=None)


Popen.wait()
等待子進程結束,設置並返回returncode屬性。
>>> p.wait()
0
注意: 若是子進程輸出了大量數據到stdout或者stderr的管道,並達到了系統pipe的緩存大小的話,
子進程會等待父進程讀取管道,而父進程此時正wait着的話,將會產生傳說中的死鎖,後果是很是嚴重滴。建議使用
communicate() 來避免這種狀況的發生。
ulimit -a
pipe size            (512 bytes, -p) 8



Popen.communicate(input=None)
和子進程交互:發送數據到stdin,並從stdout和stderr讀數據,直到收到EOF。等待子進程結束。可選的input若有有的話,要爲字符串類型。
此函數返回一個元組: (stdoutdata , stderrdata ) 。
注意,要給子進程的stdin發送數據,則Popen的時候,stdin要爲PIPE;同理,要能夠接收數據的話,stdout或者stderr也要爲PIPE。
p1=subprocess.Popen('cat /etc/passwd',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)              
>>> p2=subprocess.Popen('grep 0:0',shell=True,stdin=p1.stdout,stdout=subprocess.PIPE)
注意:讀到的數據會被緩存在內存裏,因此數據量很是大的時候要當心了。
>>> p.communicate()     
(b'Filesystem     Size    Used   Avail Capacity  Mounted on\n/dev/ad0s1a    713M    313M    343M    48%    /\ndevfs          1.0K    1.0K      0B   100%    /dev\n/dev/ad0s1e    514M    2.1M    471M     0%    /tmp\n/dev/ad0s1f    4.3G    2.5G    1.4G    64%    /usr\n/dev/ad0s1d    2.0G    121M    1.7G     6%    /var\n', None)

p=subprocess.Popen(['cat'],stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate('abc')
('abc', '')
方法的返回值取決於subprocess.Popen,若是subprocess.Popen有stdin,則p.communicate('abc')必需要傳入參數,若是沒有stdin則不須要傳入參數
是否返回stdout或stderr也是取決於subprocess.Popen,若是subprocess.Popen有定義stdout=subprocess.PIPE, stderr=subprocess.PIPE
則stdout,stderr=p.communicate('abc')
communicate:method of subprocess.Popen instance
Interact with process: Send data to stdin. Read data from
stdout and stderr, until end-of-file is reached. Wait for
process to terminate. The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child.

 

Pipe管道  
注意管道的大小
ulimit -a
pipe size            (512 bytes, -p) 8

p1 = Popen(['ls'], stdout=PIPE)
p2 = Popen(['grep', 'py'], stdin=p1.stdout, stdout=PIPE)
result = p2.stdout
for i in result:print i,

 

 



glob模塊和shlex模塊

glob模塊
glob:擴展shell通配符的
import glob
glob.glob(r'/etc/*.conf')
glob.glob(r'[a-c]?.conf') a\b\c開頭的.conf文件
glob.glob(r'[!a-c]?.conf') 不是a\b\c開頭的.conf文件

 

 

 

 

shlex模塊
import shlex
cmd = "mysql -u root -p123 -e 'show processlist'"
shlex.split(cmd)   #返回一個列表

ps ax -o pid,ppid,cmd

shlex.split()能識別引號,認爲引號裏的爲一個元素,例如:
shlex.split('ps -eo "pid lstart"')與'ps -eo "pid lstart"'.split()獲得的結果是不同的。

 


platform模塊

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
############################
# File Name: test_platform.py
# Author: frank
# Mail: frank0903@aliyun.com
# Created Time:2017-06-05 14:31:31
############################

import platform



'''
python中,platform模塊給咱們提供了不少方法去獲取操做系統的信息
如:
import platform
platform.platform() #獲取操做系統名稱及版本號,'Linux-3.13.0-46-generic-i686-with-Deepin-2014.2-trusty' 
platform.version() #獲取操做系統版本號,'#76-Ubuntu SMP Thu Feb 26 18:52:49 UTC 2015'
platform.architecture() #獲取操做系統的位數,('32bit', 'ELF')
platform.machine() #計算機類型,'i686'
platform.node() #計算機的網絡名稱,'XF654'
platform.processor() #計算機處理器信息,''i686'
platform.uname() #包含上面全部的信息彙總,('Linux', 'XF654', '3.13.0-46-generic', '#76-Ubuntu SMP Thu Feb 26 18:52:49 UTC 2015', 'i686', 'i686')

還能夠得到計算機中python的一些信息:
import platform
platform.python_build()
platform.python_compiler()
platform.python_branch()
platform.python_implementation()
platform.python_revision()
platform.python_version()
platform.python_version_tuple()
'''

# global var
# 是否顯示日誌信息
SHOW_LOG = True


def get_platform():
    '''獲取操做系統名稱及版本號'''
    return platform.platform()


def get_version():
    '''獲取操做系統版本號'''
    return platform.version()


def get_architecture():
    '''獲取操做系統的位數'''
    return platform.architecture()


def get_machine():
    '''計算機類型'''
    return platform.machine()


def get_node():
    '''計算機的網絡名稱'''
    return platform.node()


def get_processor():
    '''計算機處理器信息'''
    return platform.processor()


def get_system():
    '''獲取操做系統類型'''
    return platform.system()


def get_uname():
    '''彙總信息'''
    return platform.uname()


def get_python_build():
    ''' the Python build number and date as strings'''
    return platform.python_build()


def get_python_compiler():
    '''Returns a string identifying the compiler used for compiling Python'''
    return platform.python_compiler()


def get_python_branch():
    '''Returns a string identifying the Python implementation SCM branch'''
    return platform.python_branch()


def get_python_implementation():
    '''Returns a string identifying the Python implementation. Possible return values are: ‘CPython’, ‘IronPython’, ‘Jython’, ‘PyPy’.'''
    return platform.python_implementation()


def get_python_version():
    '''Returns the Python version as string 'major.minor.patchlevel'
    '''
    return platform.python_version()


def get_python_revision():
    '''Returns a string identifying the Python implementation SCM revision.'''
    return platform.python_revision()


def get_python_version_tuple():
    '''Returns the Python version as tuple (major, minor, patchlevel) of strings'''
    return platform.python_version_tuple()


def show_os_all_info():
    '''打印os的所有信息'''
    print('獲取操做系統名稱及版本號 : [{}]'.format(get_platform()))
    print('獲取操做系統版本號 : [{}]'.format(get_version()))
    print('獲取操做系統的位數 : [{}]'.format(get_architecture()))
    print('計算機類型 : [{}]'.format(get_machine()))
    print('計算機的網絡名稱 : [{}]'.format(get_node()))
    print('計算機處理器信息 : [{}]'.format(get_processor()))
    print('獲取操做系統類型 : [{}]'.format(get_system()))
    print('彙總信息 : [{}]'.format(get_uname()))


def show_os_info():
    '''只打印os的信息,沒有解釋部分'''
    print(get_platform())
    print(get_version())
    print(get_architecture())
    print(get_machine())
    print(get_node())
    print(get_processor())
    print(get_system())
    print(get_uname())


def show_python_all_info():
    '''打印python的所有信息'''
    print('The Python build number and date as strings : [{}]'.format(get_python_build()))
    print('Returns a string identifying the compiler used for compiling Python : [{}]'.format(get_python_compiler()))
    print('Returns a string identifying the Python implementation SCM branch : [{}]'.format(get_python_branch()))
    print('Returns a string identifying the Python implementation : [{}]'.format(get_python_implementation()))
    print('The version of Python : [{}]'.format(get_python_version()))
    print('Python implementation SCM revision : [{}]'.format(get_python_revision()))
    print('Python version as tuple : [{}]'.format(get_python_version_tuple()))


def show_python_info():
    '''只打印python的信息,沒有解釋部分'''
    print(get_python_build())
    print(get_python_compiler())
    print(get_python_branch())
    print(get_python_implementation())
    print(get_python_version())
    print(get_python_revision())
    print(get_python_version_tuple())


show_os_all_info()

 


csv模塊

 

#csv讀取
def read_csv(filepath):
    with codecs.open(filepath,'r') as f:
        csv_file=csv.reader(f)
        headers=next(csv_file) #讀表頭
        print headers
        for row in csv_file:
            print row

 

 

csv文件的讀取

csv_file=csv.reader(codecs.open(filepath,'r'))
for row in islice(csv_file, 1, None):
handle_datafieldforwindows(row)

 


csv文件的寫入

list1=['1','2']
list2=['3','4']
list3=['5','6']

out = codecs.open('C:/actordata222.csv', 'wb') #必定要以wb方式打開
# csv_writer = csv.writer(out, dialect='excel', delimiter=' ',quotechar='|') #不用逗號做爲分隔,用空格做爲分隔,那麼全部列都會合併到第一列,由於沒有了逗號
csv_writer = csv.writer(out, dialect='excel')
csv_writer.writerow(list1)
csv_writer.writerow(list2)
csv_writer.writerow(list3)

 

 


 

異常處理

異常最詳細的一個文章:https://www.cnblogs.com/EdwardTang/p/5847412.html
BaseException    全部異常的基類
SystemExit    解釋器請求退出
KeyboardInterrupt    用戶中斷執行(一般是輸入^C)
Exception    常規錯誤的基類
StopIteration    迭代器沒有更多的值
GeneratorExit    生成器(generator)發生異常來通知退出
StandardError    全部的內建標準異常的基類
ArithmeticError    全部數值計算錯誤的基類
FloatingPointError    浮點計算錯誤
OverflowError    數值運算超出最大限制
ZeroDivisionError    除(或取模)零 (全部數據類型)
AssertionError    斷言語句失敗
AttributeError    對象沒有這個屬性
EOFError    沒有內建輸入,到達EOF 標記
EnvironmentError    操做系統錯誤的基類
IOError    輸入/輸出操做失敗
OSError    操做系統錯誤
WindowsError    系統調用失敗
ImportError    導入模塊/對象失敗
LookupError    無效數據查詢的基類
IndexError    序列中沒有此索引(index)
KeyError    映射中沒有這個鍵
MemoryError    內存溢出錯誤(對於Python 解釋器不是致命的)
NameError    未聲明/初始化對象 (沒有屬性)
UnboundLocalError    訪問未初始化的本地變量
ReferenceError    弱引用(Weak reference)試圖訪問已經垃圾回收了的對象
RuntimeError    通常的運行時錯誤
NotImplementedError    還沒有實現的方法
SyntaxError    Python 語法錯誤
IndentationError    縮進錯誤
TabError    Tab 和空格混用
SystemError    通常的解釋器系統錯誤
TypeError    對類型無效的操做
ValueError    傳入無效的參數
UnicodeError    Unicode 相關的錯誤
UnicodeDecodeError    Unicode 解碼時的錯誤
UnicodeEncodeError    Unicode 編碼時錯誤
UnicodeTranslateError    Unicode 轉換時錯誤
Warning    警告的基類
DeprecationWarning    關於被棄用的特徵的警告
FutureWarning    關於構造未來語義會有改變的警告
OverflowWarning    舊的關於自動提高爲長整型(long)的警告
PendingDeprecationWarning    關於特性將會被廢棄的警告
RuntimeWarning    可疑的運行時行爲(runtime behavior)的警告
SyntaxWarning    可疑的語法的警告
UserWarning    用戶代碼生成的警告

若是函數中用到全局變量而且修改了它,那麼須要在函數裏的變量前加global關鍵字
系統沒法判斷你是對全局變量仍是局部變量作操做,若是不加global關鍵字,會報錯UnboundLocalError ,若是沒有修改/賦值,就不用加global關鍵字
l=[1,2]

def f():
    l.append(4)
    
不會報UnboundLocalError 

l=[1,2]

def f():
    l[5]
    
會報UnboundLocalError 

 

KeyboardInterrupt

 

 

自定義異常

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#__author__="huazai"
"""
測試
Date:2016.08.12
"""

import subprocess
try:
    subprocess.check_call('exit 1', shell=True) # shell裏面退出碼非0會觸發異常
except subprocess.CalledProcessError:
    print 'call fail'
except Exception, e:
    print e
print 'hello world'

 

 

自定義異常,繼承Exception根類

class FuncError(Exception):
def __str__(self):
    return "I am a funError"

def func():
    raise FuncError()

func()
#try:
# func()
#except FuncError, e:
# print e
print 'hello world'

 

 

#若是不知道異常的類型,就寫Exception,Exception是總的異常

func()

try:
    func()
except Exception , e:
    print e

 



#若是有多個異常,那麼只會捕獲第一個匹配到的異常

func()
try:
     func()
except NameError, e:
     print e
except IndexError, e:
     print e
except ValueError, e:
     print e
     
e表示一個變量,保存異常的信息
固然這個變量名隨便起,好比
except NameError, a:
     print a

 

 

 


異常在try塊裏拋。
finally:不管try塊是否拋異常,永遠執行的代碼,一般用來執行關閉文件,斷開服務器鏈接的功能。

try無異常,纔會執行else
語法格式

try:

except:

else:

finally:

 

python中的兩個else
一、while循環或for循環中,不建議使用else

while True:
...
else:
...

 

二、try...except,建議使用else

try:
...
except:
...
else:
...
finally:
...

else設計得特別好,其餘語言也應該吸收這個設計,這個設計的語義是執行try裏面語句,裏面的語句可能出現異常,
若是出現異常,就執行except裏面的語句
若是沒有出現異常,就執行else裏面語句,不管是否出現異常,都要執行finally語句,這個設計就好在else語句徹底和咱們直觀感覺是同樣的,是在沒有出現異常的狀況下執行,
而且,有else比沒有else好,有else之後,正確將程序員認爲可能出現的異常代碼和不可能出現異常的代碼分開,更加清楚代表哪一條語句可能會出現異常

def write(sql, vars):
    """
    鏈接pg數據庫並進行寫的操做
    若是鏈接失敗,會把錯誤寫入日誌中,並返回false,若是sql執行失敗,也會把錯誤寫入日誌中,並返回false,若是全部執行正常,則返回true
    """
    try:
        # 鏈接數據庫
        conn = psycopg2.connect(database=db_name, user=db_user, password=db_pass, host=db_host, port=db_port)
        # 獲取遊標
        cursor = conn.cursor()
    except Exception as e:
        print(e.args)
        log_helper.error('鏈接數據庫失敗:' + str(e.args))
        return False
    try:
        # 執行sql語句
        cursor.execute(sql, vars)
        # 提交事務
        conn.commit()
    except Exception as e:
        print(e.args)
        # 若是出錯,則事務回滾
        conn.rollback()
        log_helper.error('sql執行失敗:' + str(e.args) + ' sql:' + str(sql))
        return False
    else:
        # 獲取數據
        try:
            data = [dict((cursor.description[i][0], value) for i, value in enumerate(row))
                         for row in cursor.fetchall()]
        except Exception as e:
            # 沒有設置returning或執行修改或刪除語句時,記錄不存在
            data = None
    finally:
        # 關閉遊標和數據庫連接
        cursor.close()
        conn.close()

    # 若是寫入數據後,將數據庫返回的數據返回給調用者
    return data
相關文章
相關標籤/搜索