目录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第十二天 收集主机信息 正则表达式 无名分组 有名分组
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) !!!
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