Python之路4--模块
[toc]模块,用一砣代码实现了某个功能的代码集合。类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的 `.py` 文件中),n 个 `.py` 文件组成的代码集合就称为模块。如:`os` 是系统相关的模块;`file` 是文件操作相关的模块模块分为三种:* 自定义模块* 内置模块* 开源模块## 1. 自定义模块### 1.1 定义模块情景一:情景二:情景三:### 1.2 导入模块Python 之所以应用越来越广泛,在一定程度上也依赖于其为程序员提供了大量的模块以供使用,如果想要使用模块,则需要导入。导入模块有一下几种方法: ```pythonimport modulefrom module.xx.xx import xxfrom module.xx.xx import xx as rename from module.xx.xx import *```导入模块其实就是告诉 Python 解释器去解释那个 py 文件* 导入一个 `py` 文件,解释器解释该 `py` 文件* 导入一个包,解释器解释该包下的 `__init__.py` 文件那么问题来了,导入模块时是根据那个路径作为基准来进行的呢?即:`sys.path````pythonimport sysprint sys.path```如果 `sys.path` 路径列表没有你想要的路径,可以通过 `sys.path.append('路径')` 添加。通过 `os` 模块可以获取各种目录,例如:```pythonimport ospre_path = os.path.abspath('../')sys.path.append(pre_path)```## 2. 开源模块### 2.1 下载安装下载安装有两种方式:方式一:```pythonyumpipapt-get```方式二:```python下载源码解压源码进入目录编译源码 python setup.py build安装源码 python setup.py install```注:在使用源码安装时,需要使用到 `gcc` 编译和 python 开发环境,所以,需要先执行:```pythonyum install gccyum install python-devel或apt-get python-dev```安装成功后,模块会自动安装到 `sys.path` 中的某个目录中,如:```python/usr/lib/python2.7/site-packages/```### 2.2 导入模块同自定义模块中导入的方式### 2.3 模块 paramiko`paramiko` 是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,`fabric` 和 `ansible` 内部的远程管理就是使用的 `paramiko` 来现实。#### 2.3.1 下载安装```pythonpip3 install paramiko```或```python# pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto # 下载安装 pycryptowget http://files.cnblogs.com/files/wupeiqi/pycrypto-2.6.1.tar.gztar -xvf pycrypto-2.6.1.tar.gzcd pycrypto-2.6.1python setup.py buildpython setup.py install # 进入python环境,导入Crypto检查是否安装成功# 下载安装 paramikowget http://files.cnblogs.com/files/wupeiqi/paramiko-1.10.1.tar.gztar -xvf paramiko-1.10.1.tar.gzcd paramiko-1.10.1python setup.py buildpython setup.py install # 进入python环境,导入paramiko检查是否安装成功```#### 2.3.2 使用模块```python# filename:执行命令 - 通过用户名和密码连接服务器.pyimport paramikossh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect('192.168.1.108', 22, 'alex', '123')stdin, stdout, stderr = ssh.exec_command('df')print stdout.read()ssh.close();``````python# filename:执行命令 - 过密钥链接服务器.pyimport paramikoprivate_key_path = '/home/auto/.ssh/id_rsa'key = paramiko.RSAKey.from_private_key_file(private_key_path)ssh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect('主机名 ', 端口, '用户名', key)stdin, stdout, stderr = ssh.exec_command('df')print stdout.read()ssh.close()``````python# filename:上传或者下载文件 - 通过用户名和密码.pyimport os,sysimport paramikot = paramiko.Transport(('182.92.219.86',22))t.connect(username='wupeiqi',password='123')sftp = paramiko.SFTPClient.from_transport(t)sftp.put('/tmp/test.py','/tmp/test.py')t.close()import os,sysimport paramikot = paramiko.Transport(('182.92.219.86',22))t.connect(username='wupeiqi',password='123')sftp = paramiko.SFTPClient.from_transport(t)sftp.get('/tmp/test.py','/tmp/test2.py')t.close()``````python# filename:上传或下载文件 - 通过密钥.pyimport paramikopravie_key_path = '/home/auto/.ssh/id_rsa'key = paramiko.RSAKey.from_private_key_file(pravie_key_path)t = paramiko.Transport(('182.92.219.86',22))t.connect(username='wupeiqi',pkey=key)sftp = paramiko.SFTPClient.from_transport(t)sftp.put('/tmp/test3.py','/tmp/test3.py')t.close()import paramikopravie_key_path = '/home/auto/.ssh/id_rsa'key = paramiko.RSAKey.from_private_key_file(pravie_key_path)t = paramiko.Transport(('182.92.219.86',22))t.connect(username='wupeiqi',pkey=key)sftp = paramiko.SFTPClient.from_transport(t)sftp.get('/tmp/test3.py','/tmp/test4.py')t.close()```## 3. 内置模块### 3.1 os用于提供系统级别的操作```pythonos.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cdos.curdir 返回当前目录: ('.')os.pardir 获取当前目录的父目录字符串名:('..')os.makedirs('hxl/abc') 可生成多层递归目录os.removedirs('hxl') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirnameos.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirnameos.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印os.remove() 删除一个文件os.rename("oldname","newname") 重命名文件/目录os.stat('path/filename') 获取文件/目录信息os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"os.pathsep 输出用于分割文件路径的字符串os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'os.system("bash command") 运行shell命令,直接显示os.environ 获取系统环境变量os.path.abspath(path) 返回path规范化的绝对路径os.path.split(path) 将path分割成目录和文件名二元组返回os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素os.path.exists(path) 如果path存在,返回True;如果path不存在,返回Falseos.path.isabs(path) 如果path是绝对路径,返回Trueos.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回Falseos.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回Falseos.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间```更多[猛击这里](https://docs.python.org/2/library/os.html?highlight=os#module-os)### 3.2 sys用于提供对解释器相关的操作```pythonsys.argv 命令行参数List,第一个元素是程序本身路径sys.exit(n) 退出程序,正常退出时exit(0)sys.version 获取Python解释程序的版本信息sys.maxint 最大的Int值sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值sys.platform 返回操作系统平台名称sys.stdout.write('please:')val = sys.stdin.readline()[:-1]```更多[猛击这里](https://docs.python.org/2/library/sys.html?highlight=sys#module-sys)### 3.3 hashlib 用于加密相关的操作,代替了 `md5` 模块和 `sha` 模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法```python# filename:md5-废弃.pyimport md5hash = md5.new()hash.update('admin')print hash.hexdigest()``````python# filename:sha-废弃.pyimport shahash = sha.new()hash.update('admin')print hash.hexdigest()``````pythonimport hashlib # ######## md5 ######## hash = hashlib.md5()hash.update('admin')print hash.hexdigest() # ######## sha1 ######## hash = hashlib.sha1()hash.update('admin')print hash.hexdigest() # ######## sha256 ######## hash = hashlib.sha256()hash.update('admin')print hash.hexdigest() # ######## sha384 ######## hash = hashlib.sha384()hash.update('admin')print hash.hexdigest() # ######## sha512 ######## hash = hashlib.sha512()hash.update('admin')print hash.hexdigest()```以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。```pythonimport hashlib # ######## md5 ######## hash = hashlib.md5('898oaFs09f')hash.update('admin')print hash.hexdigest()```python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密```pythonimport hmach = hmac.new('wueiqi')h.update('hellowo')print h.hexdigest()```### 3.4 json 和 pickle 用于序列化的两个模块* `json`,用于字符串 和 python 数据类型间进行转换* `pickle`,用于 python 特有的类型 和 python 的数据类型间进行转换`Json` 模块提供了四个功能:dumps、dump、loads、load`pickle` 模块提供了四个功能:dumps、dump、loads、load```pythonimport pickledata = {'k1': 123, 'k2': 'hello'}# pickle.dumps 将数据通过特殊的形式转换为只有 python 语言认识的字符串p_str = pickle.dumps(data)print p_str# pickle.dump 将数据通过特殊的形式转换为只有 python 语言认识的字符串,并写入文件with open('/result.pk', 'w') as fp: pickle.dump(data, fp) import json# json.dumps 将数据通过特殊的形式转换为所有程序语言都认识的字符串j_str = json.dumps(data)print j_str# json.dumps 将数据通过特殊的形式转换为所有程序语言都认识的字符串,并写入文件with open('/result.json', 'w') as fp: json.dump(data, fp)```### 3.5 执行系统命令 可以执行shell命令的相关模块和函数有:* os.system* os.spawn** os.popen* --废弃* popen2.* --废弃* commands.* --废弃,3.x中被移除```python# filename:commands.pyimport commandsresult = commands.getoutput('cmd')result = commands.getstatus('cmd')result = commands.getstatusoutput('cmd')```以上执行 shell 命令的相关的模块和函数的功能均在 `subprocess` 模块中实现,并提供了更丰富的功能。#### 3.5.1 call 执行命令,返回状态码```pythonret = subprocess.call(["ls", "-l"], shell=False)ret = subprocess.call("ls -l", shell=True)```shell = True ,允许 shell 命令是字符串形式#### 3.5.2 check_call执行命令,如果执行状态码是 0 ,则返回0,否则抛异常```pythonsubprocess.check_call(["ls", "-l"])subprocess.check_call("exit 1", shell=True)```#### 3.5.3 check_output执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常```pythonsubprocess.check_output(["echo", "Hello World!"])subprocess.check_output("exit 1", shell=True)```#### 3.5.4 subprocess.Popen(...)用于执行复杂的系统命令参数:* args:shell命令,可以是字符串或者序列类型(如:list,元组)* bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲* stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄* preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用* close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。* 所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。* shell:同上* cwd:用于设置子进程的当前目录* env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。* universal_newlines:不同系统的换行符不同,True -> 同意使用 \n* startupinfo与createionflags只在windows下有效将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等```pythonimport subprocessret1 = subprocess.Popen(["mkdir","t1"])ret2 = subprocess.Popen("mkdir t2", shell=True)```终端输入的命令分为两种:* 即可得到输出,如:ifconfig* 输入进行某环境,依赖再输入,如:python```pythonimport subprocessret1 = subprocess.Popen(["mkdir","t1"])ret2 = subprocess.Popen("mkdir t2", shell=True)``````pythonimport subprocessobj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)``````pythonimport subprocessobj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)obj.stdin.write('print 1 \n ')obj.stdin.write('print 2 \n ')obj.stdin.write('print 3 \n ')obj.stdin.write('print 4 \n ')obj.stdin.close()cmd_out = obj.stdout.read()obj.stdout.close()cmd_error = obj.stderr.read()obj.stderr.close()print cmd_outprint cmd_error``````pythonimport subprocessobj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)obj.stdin.write('print 1 \n ')obj.stdin.write('print 2 \n ')obj.stdin.write('print 3 \n ')obj.stdin.write('print 4 \n ')out_error_list = obj.communicate()print out_error_list```更多[猛击这里](https://docs.python.org/2/library/subprocess.html?highlight=subprocess#frequently-used-arguments)### 3.6 shutil高级的 文件、文件夹、压缩包 处理模块#### 3.6.1 shutil.copyfileobj(fsrc, fdst[, length])将文件内容拷贝到另一个文件中,可以部分内容```pythondef copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf)```#### 3.6.2 shutil.copyfile(src, dst)拷贝文件```pythondef copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) for fn in [src, dst]: try: st = os.stat(fn) except OSError: # File most likely does not exist pass else: # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) with open(src, 'rb') as fsrc: with open(dst, 'wb') as fdst: copyfileobj(fsrc, fdst)```#### 3.6.3 shutil.copymode(src, dst)仅拷贝权限。内容、组、用户均不变```pythondef copymode(src, dst): """Copy mode bits from src to dst""" if hasattr(os, 'chmod'): st = os.stat(src) mode = stat.S_IMODE(st.st_mode) os.chmod(dst, mode)```#### 3.6.4 shutil.copystat(src, dst)拷贝状态的信息,包括:mode bits, atime, mtime, flags```pythondef copystat(src, dst): """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) if hasattr(os, 'chflags') and hasattr(st, 'st_flags'): try: os.chflags(dst, st.st_flags) except OSError, why: for err in 'EOPNOTSUPP', 'ENOTSUP': if hasattr(errno, err) and why.errno == getattr(errno, err): break else: raise```#### 3.6.5 shutil.copy(src, dst)拷贝文件和权限```pythondef copy(src, dst): """Copy data and mode bits ("cp src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copymode(src, dst)```#### 3.6.6 shutil.copy2(src, dst)拷贝文件和状态信息```pythondef copy2(src, dst): """Copy data and all stat info ("cp -p src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copystat(src, dst)```#### 3.6.7 shutil.ignore_patterns(*patterns)#### 3.6.8 shutil.copytree(src, dst, symlinks=False, ignore=None)递归的去拷贝文件例如:`copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))````pythondef ignore_patterns(*patterns): """Function that can be used as copytree() ignore parameter. Patterns is a sequence of glob-style patterns that are used to exclude files""" def _ignore_patterns(path, names): ignored_names = [] for pattern in patterns: ignored_names.extend(fnmatch.filter(names, pattern)) return set(ignored_names) return _ignore_patternsdef copytree(src, dst, symlinks=False, ignore=None): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. The optional ignore argument is a callable. If given, it is called with the `src` parameter, which is the directory being visited by copytree(), and `names` which is the list of `src` contents, as returned by os.listdir(): callable(src, names) -> ignored_names Since copytree() is called recursively, the callable will be called once for each directory that is copied. It returns a list of names relative to the `src` directory that should not be copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored_names = set() os.makedirs(dst) errors = [] for name in names: if name in ignored_names: continue srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks, ignore) else: # Will raise a SpecialFileError for unsupported file types copy2(srcname, dstname) # catch the Error from the recursive copytree so that we can # continue with other files except Error, err: errors.extend(err.args[0]) except EnvironmentError, why: errors.append((srcname, dstname, str(why))) try: copystat(src, dst) except OSError, why: if WindowsError is not None and isinstance(why, WindowsError): # Copying file access times may fail on Windows pass else: errors.append((src, dst, str(why))) if errors: raise Error, errors```#### 3.6.9 shutil.rmtree(path[, ignore_errors[, onerror]])递归的去删除文件```pythondef rmtree(path, ignore_errors=False, onerror=None): """Recursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised. """ if ignore_errors: def onerror(*args): pass elif onerror is None: def onerror(*args): raise try: if os.path.islink(path): # symlinks to directories are forbidden, see bug #1669 raise OSError("Cannot call rmtree on a symbolic link") except OSError: onerror(os.path.islink, path, sys.exc_info()) # can't continue even if onerror hook returns return names = [] try: names = os.listdir(path) except os.error, err: onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) try: mode = os.lstat(fullname).st_mode except os.error: mode = 0 if stat.S_ISDIR(mode): rmtree(fullname, ignore_errors, onerror) else: try: os.remove(fullname) except os.error, err: onerror(os.remove, fullname, sys.exc_info()) try: os.rmdir(path) except os.error: onerror(os.rmdir, path, sys.exc_info())```#### 3.6.10 shutil.move(src, dst)递归的去移动文件```pythondef move(src, dst): """Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics. If the destination is on our current filesystem, then rename() is used. Otherwise, src is copied to the destination and then removed. A lot more could be done here... A look at a mv.c shows a lot of the issues this implementation glosses over. """ real_dst = dst if os.path.isdir(dst): if _samefile(src, dst): # We might be on a case insensitive filesystem, # perform the rename anyway. os.rename(src, dst) return real_dst = os.path.join(dst, _basename(src)) if os.path.exists(real_dst): raise Error, "Destination path '%s' already exists" % real_dst try: os.rename(src, real_dst) except OSError: if os.path.isdir(src): if _destinsrc(src, dst): raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst) copytree(src, real_dst, symlinks=True) rmtree(src) else: copy2(src, real_dst) os.unlink(src)```#### 3.6.11 shutil.make_archive(base_name, format,...)创建压缩包并返回文件路径,例如:zip、tar* base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,如:www =>保存至当前路径如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/* format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”* root_dir: 要压缩的文件夹路径(默认当前目录)* owner: 用户,默认当前用户* group: 组,默认当前组* logger: 用于记录日志,通常是logging.Logger对象```python#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录 import shutilret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test') #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录import shutilret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')``````pythondef make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "bztar" or "gztar". 'root_dir' is a directory that will be the root directory of the archive; ie. we typically chdir into 'root_dir' before creating the archive. 'base_dir' is the directory where we start archiving from; ie. 'base_dir' will be the common prefix of all files and directories in the archive. 'root_dir' and 'base_dir' both default to the current directory. Returns the name of the archive file. 'owner' and 'group' are used when creating a tar archive. By default, uses the current owner and group. """ save_cwd = os.getcwd() if root_dir is not None: if logger is not None: logger.debug("changing into '%s'", root_dir) base_name = os.path.abspath(base_name) if not dry_run: os.chdir(root_dir) if base_dir is None: base_dir = os.curdir kwargs = {'dry_run': dry_run, 'logger': logger} try: format_info = _ARCHIVE_FORMATS[format] except KeyError: raise ValueError, "unknown archive format '%s'" % format func = format_info[0] for arg, val in format_info[1]: kwargs[arg] = val if format != 'zip': kwargs['owner'] = owner kwargs['group'] = group try: filename = func(base_name, base_dir, **kwargs) finally: if root_dir is not None: if logger is not None: logger.debug("changing back to '%s'", save_cwd) os.chdir(save_cwd) return filename```shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:```python# filename:zipfile 压缩解压.pyimport zipfile# 压缩z = zipfile.ZipFile('laxi.zip', 'w')z.write('a.log')z.write('data.data')z.close()# 解压z = zipfile.ZipFile('laxi.zip', 'r')z.extractall()z.close()``````python# filename:tarfile 压缩解压.pyimport tarfile# 压缩tar = tarfile.open('your.tar','w')tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')tar.close()# 解压tar = tarfile.open('your.tar','r')tar.extractall() # 可设置解压地址tar.close()```### 3.7 ConfigParser用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。```python# 注释1; 注释2 [section1]k1 = v1k2:v2 [section2]k1 = v1``````pythonimport ConfigParser config = ConfigParser.ConfigParser()config.read('i.cfg') # ########## 读 ###########secs = config.sections()#print secs#options = config.options('group2')#print options #item_list = config.items('group2')#print item_list #val = config.get('group1','key')#val = config.getint('group1','key') # ########## 改写 ###########sec = config.remove_section('group1')#config.write(open('i.cfg', "w")) #sec = config.has_section('wupeiqi')#sec = config.add_section('wupeiqi')#config.write(open('i.cfg', "w")) #config.set('group2','k1',11111)#config.write(open('i.cfg', "w")) #config.remove_option('group2','age')#config.write(open('i.cfg', "w"))```### 3.8 logging用于便捷记录日志且线程安全的模块```pythonimport logging logging.basicConfig(filename='log.log', format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p', level=10) logging.debug('debug')logging.info('info')logging.warning('warning')logging.error('error')logging.critical('critical')logging.log(10,'log')```对于等级:```pythonCRITICAL = 50FATAL = CRITICALERROR = 40WARNING = 30WARN = WARNINGINFO = 20DEBUG = 10NOTSET = 0```只有大于当前日志等级的操作才会被记录。对于格式,有如下属性可是配置:### 3.9 time时间相关的操作,时间有三种表示方式:* 时间戳 1970年1月1日之后的秒,即:time.time()* 格式化的字符串 2014-11-11 11:11, 即:time.strftime('%Y-%m-%d')* 结构化时间 元组包含了:年、日、星期等... time.struct_time 即:time.localtime()```pythonprint time.time()print time.mktime(time.localtime()) print time.gmtime() #可加时间戳参数print time.localtime() #可加时间戳参数print time.strptime('2014-11-11', '%Y-%m-%d') print time.strftime('%Y-%m-%d') #默认当前时间print time.strftime('%Y-%m-%d',time.localtime()) #默认当前时间print time.asctime()print time.asctime(time.localtime())print time.ctime(time.time()) import datetime'''datetime.date:表示日期的类。常用的属性有year, month, daydatetime.time:表示时间的类。常用的属性有hour, minute, second, microseconddatetime.datetime:表示日期时间datetime.timedelta:表示时间间隔,即两个时间点之间的长度timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])strftime("%Y-%m-%d")'''import datetimeprint datetime.datetime.now()print datetime.datetime.now() - datetime.timedelta(days=5)```### 3.10 re re模块用于对python的正则表达式的操作。字符: . 匹配除换行符以外的任意字符 \w 匹配字母或数字或下划线或汉字 \s 匹配任意的空白符 \d 匹配数字 \b 匹配单词的开始或结束 ^ 匹配字符串的开始 $ 匹配字符串的结束次数: * 重复零次或更多次 + 重复一次或更多次 ? 重复零次或一次 {n} 重复n次 {n,} 重复n次或更多次 {n,m} 重复n到m次```pythonIP:^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$手机号:^1[3|4|5|8][0-9]\d{8}$```#### 3.10.1 match(pattern, string, flags=0)从起始位置开始根据模型去字符串中匹配指定内容,匹配单个* 正则表达式* 要匹配的字符串* 标志位,用于控制正则表达式的匹配方式```pythonimport reobj = re.match('\d+', '123uuasf')if obj: print obj.group()``````python# filename:flags.pyI = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore caseL = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit localeU = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode localeM = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newlineS = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newlineX = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments```#### 3.10.2 search(pattern, string, flags=0)根据模型去字符串中匹配指定内容,匹配单个```pythonimport reobj = re.search('\d+', 'u123uu888asf')if obj: print obj.group()```#### 3.10.3 group和groups```pythona = "123abc456"print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group()print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(0)print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(1)print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(2)print re.search("([0-9]*)([a-z]*)([0-9]*)", a).groups()```#### 3.10.4 findall(pattern, string, flags=0)上述两中方式均用于匹配单值,即:只能匹配字符串中的一个,如果想要匹配到字符串中所有符合条件的元素,则需要使用 findall。```pythonimport reobj = re.findall('\d+', 'fa123uu888asf')print obj```#### 3.10.5 sub(pattern, repl, string, count=0, flags=0)用于替换匹配的字符串```pythoncontent = "123abc456"new_content = re.sub('\d+', 'sb', content)# new_content = re.sub('\d+', 'sb', content, 1)print new_content```相比于str.replace功能更加强大#### 3.10.6 split(pattern, string, maxsplit=0, flags=0)根据指定匹配进行分组```pythoncontent = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"new_content = re.split('\*', content)# new_content = re.split('\*', content, 1)print new_content``````pythoncontent = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"new_content = re.split('[\+\-\*\/]+', content)# new_content = re.split('\*', content, 1)print new_content``````pythoninpp = '1-2*((60-30 +(-40-5)*(9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))'inpp = re.sub('\s*','',inpp)new_content = re.split('\(([\+\-\*\/]?\d+[\+\-\*\/]?\d+){1}\)', inpp, 1)print new_content```相比于str.split更加强大 ### 实例:计算器源码```python# filename:计算器源码.py"""基于递归和正则表达式实现的计算器,源码如下:该计算器思路: 1、递归寻找表达式中只含有 数字和运算符的表达式,并计算结果 2、由于整数计算会忽略小数,所有的数字都认为是浮点型操作,以此来保留小数使用技术: 1、正则表达式 2、递归执行流程如下:******************** 请计算表达式: 1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) ) ********************before: ['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']-40.0/5=-8.0after: ['1-2*((60-30+-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']========== 上一次计算结束 ==========before: ['1-2*((60-30+-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']9-2*5/3+7/3*99/4*2998+10*568/14=173545.880953after: ['1-2*((60-30+-8.0*173545.880953)-(-4*3)/(16-3*2))']========== 上一次计算结束 ==========before: ['1-2*((60-30+-8.0*173545.880953)-(-4*3)/(16-3*2))']60-30+-8.0*173545.880953=-1388337.04762after: ['1-2*(-1388337.04762-(-4*3)/(16-3*2))']========== 上一次计算结束 ==========before: ['1-2*(-1388337.04762-(-4*3)/(16-3*2))']-4*3=-12.0after: ['1-2*(-1388337.04762--12.0/(16-3*2))']========== 上一次计算结束 ==========before: ['1-2*(-1388337.04762--12.0/(16-3*2))']16-3*2=10.0after: ['1-2*(-1388337.04762--12.0/10.0)']========== 上一次计算结束 ==========before: ['1-2*(-1388337.04762--12.0/10.0)']-1388337.04762--12.0/10.0=-1388335.84762after: ['1-2*-1388335.84762']========== 上一次计算结束 ==========我的计算结果: 2776672.69524"""import redef compute_mul_div(arg): """ 操作乘除 :param expression:表达式 :return:计算结果 """ val = arg[0] mch = re.search('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val) if not mch: return content = re.search('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val).group() if len(content.split('*')) > 1: n1, n2 = content.split('*') value = float(n1) * float(n2) else: n1, n2 = content.split('/') value = float(n1) / float(n2) before, after = re.split('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val, 1) new_str = "%s%s%s" % (before, value, after) arg[0] = new_str compute_mul_div(arg)def compute_add_sub(arg): """ 操作加减 :param expression:表达式 :return:计算结果 """ while True: if arg[0].__contains__('+-') or arg[0].__contains__("++") or arg[0].__contains__('-+') or arg[0].__contains__( "--"): arg[0] = arg[0].replace('+-', '-') arg[0] = arg[0].replace('++', '+') arg[0] = arg[0].replace('-+', '-') arg[0] = arg[0].replace('--', '+') else: break if arg[0].startswith('-'): arg[1] += 1 arg[0] = arg[0].replace('-', '&') arg[0] = arg[0].replace('+', '-') arg[0] = arg[0].replace('&', '+') arg[0] = arg[0][1:] val = arg[0] mch = re.search('\d+\.*\d*[\+\-]{1}\d+\.*\d*', val) if not mch: return content = re.search('\d+\.*\d*[\+\-]{1}\d+\.*\d*', val).group() if len(content.split('+')) > 1: n1, n2 = content.split('+') value = float(n1) + float(n2) else: n1, n2 = content.split('-') value = float(n1) - float(n2) before, after = re.split('\d+\.*\d*[\+\-]{1}\d+\.*\d*', val, 1) new_str = "%s%s%s" % (before, value, after) arg[0] = new_str compute_add_sub(arg)def compute(expression): """ 操作加减乘除 :param expression:表达式 :return:计算结果 """ inp = [expression, 0] # 处理表达式中的乘除 compute_mul_div(inp) # 处理 compute_add_sub(inp) if divmod(inp[1], 2)[1] == 1: result = float(inp[0]) result = result * -1 else: result = float(inp[0]) return resultdef exec_bracket(expression): """ 递归处理括号,并计算 :param expression: 表达式 :return:最终计算结果 """ # 如果表达式中已经没有括号,则直接调用负责计算的函数,将表达式结果返回,如:2*1-82+444 if not re.search('\(([\+\-\*\/]*\d+\.*\d*){2,}\)', expression): final = compute(expression) return final # 获取 第一个 只含有 数字/小数 和 操作符 的括号 # 如: # ['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] # 找出:(-40.0/5) content = re.search('\(([\+\-\*\/]*\d+\.*\d*){2,}\)', expression).group() # 分割表达式,即: # 将['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] # 分割更三部分:['1-2*((60-30+( (-40.0/5) *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] before, nothing, after = re.split('\(([\+\-\*\/]*\d+\.*\d*){2,}\)', expression, 1) print 'before:', expression content = content[1:len(content) - 1] # 计算,提取的表示 (-40.0/5),并活的结果,即:-40.0/5=-8.0 ret = compute(content) print '%s=%s' % (content, ret) # 将执行结果拼接,['1-2*((60-30+( -8.0 *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] expression = "%s%s%s" % (before, ret, after) print 'after:', expression print "=" * 10, '上一次计算结束', "=" * 10 # 循环继续下次括号处理操作,本次携带者的是已被处理后的表达式,即: # ['1-2*((60-30+ -8.0 *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] # 如此周而复始的操作,直到表达式中不再含有括号 return exec_bracket(expression)# 使用 __name__ 的目的:# 只有执行 python index.py 时,以下代码才执行# 如果其他人导入该模块,以下代码不执行if __name__ == "__main__": # print '*'*20,"请计算表达式:", "1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )" ,'*'*20 # inpp = '1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) ) ' inpp = "1-2*-30/-12*(-20+200*-3/-200*-300-100)" # inpp = "1-5*980.0" inpp = re.sub('\s*', '', inpp) # 表达式保存在列表中 result = exec_bracket(inpp) print result```