Python第十一天 异常处理 glob模块和shlex模块 打开外部程序和subprocess模块 subprocess类 Pipe管道 operator模块 sorted函数 os模块 hashlib模块 platform模块 csv模块

Python第十一天    异常处理  glob模块和shlex模块    打开外部程序和subprocess模块  subprocess类  Pipe管道  operator模块   sorted函数    os模块   hashlib模块  platform模块  csv模块

目录

Pycharm使用技巧(转载)

Python第一天  安装  shell  文件

Python第二天  变量  运算符与表达式  input()与raw_input()区别  字符编码  python转义符  字符串格式化

Python第三天 序列  5种数据类型  数值  字符串  列表  元组  字典

Python第四天   流程控制   if else条件判断   for循环 while循环

Python第五天   文件访问    for循环访问文件    while循环访问文件   字符串的startswith函数和split函数

Python第六天   类型转换

Python第七天   函数  函数参数   函数变量   函数返回值  多类型传值    冗余参数   函数递归调用   匿名函数   内置函数   列表表达式/列表重写

Python第八天  模块   包   全局变量和内置变量__name__    Python path

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
环境变量
设置系统环境变量
1、os.environ['环境变量名称']='环境变量值' #其中key和value均为string类型
2、os.putenv('环境变量名称', '环境变量值')

获取系统环境变量
1、os.environ['环境变量名称']
2、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://*.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([], args[], ...])

注意:当调用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=[']
list2=[']
list3=[']

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
1、while循环或for循环中,不建议使用else

while True:
...
else:
...

2、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
上一篇:ios开发ios9新特性关键字学习:泛型,逆变,协变,__kindof


下一篇:在net中json序列化与反序列化 面向对象六大原则 (第一篇) 一步一步带你了解linq to Object 10分钟浅谈泛型协变与逆变