《Python3.6官方文档》– 第十章
os 模块提供一系列与操作系统进行交互的函数。
import os os.getcwd() # 返回当前工作目录 os.chdir(/server/accesslogs) # 修改当前工作目录 os.system(mkdir today) # 在系统shell中运行mkdir命令
确保使用 import os 而不是 from os import * .它将导致os.open()覆盖隐式内建函数open(),它们是完全不同的.
诸如os等大模块工作时,一些内建函数dir() , help()的交互式帮助是很有用的.
import os dir(os) help(os)
针对日常的文件、目录的管理任务,shutil模块提供了易用的高级接口.
import shutil shutil.copyfile(data.db, archive.db) shutil.move(/build/executables, installdir)文件通配符
glob 模块提供了通过通配符列出文件列表的功能.
import glob glob.glob(*.py)命令行参数
常见的实用脚本通常需要处理命令行参数,这些参数以list的形式存储在sys 模块的argv属性中.
使用下面的代码运行python demo.py one two three`
import sys print(sys.argv) [demo.py, one, two, three]
getopt 模块约定使用Unix的 getopt() 函数处理sys.argv,argparse 模块提供了更强大易拓展的命令行处理流程.
错误输出重定向 程序终止[sys]模块拥有 stdin,stdout和stderr属性,stderr是很有用的,即使在stdout被重定向后,由它发出警告和错误信息也都是可见的.
sys.stderr.write(Warning, log file not found starting a new one/n)
sys.exit() 是停掉脚本最直接的方式
字符模式匹配re 模块为高级的字符处理提供了正则表达式工具. 针对复杂的匹配和处理,正则表达式提供了简明的解决方式.
import re re.findall(r/bf[a-z]*, which foot or hand fell fastest) re.sub(r(/b[a-z]+) /1, r/1, cat in the the hat)
当仅仅需要一些简单的功能时,string 方法是更合适的选择,它的可读性更高,更易进行debug.
tea for too.replace(too, two)
math 模块为浮点运算提供了基于C library 函数的入口
import math math.cos(math.pi / 4) math.log(1024, 2) random 模块提供了进行随机选择的工具.
import random random.choice([apple, pear, banana]) random.sample(range(100), 10) # sampling without replacement random.random() # random float random.randrange(6) # random integer chosen from range(6)
statistic模块计算数值的基本统计属性(均值,中位数,方差等)
import statistics data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] statistics.mean(data) statistics.median(data) statistics.variance(data)
SciPy 工程有很多进行数值运算的模块
接入互联网有很多模块可用于接入互联网并处理互联网协议,这里列举两个最简单的:
urllib.request 从互联网地址获取数据from urllib.request import urlopen with urlopen(http://tycho.usno.navy.mil/cgi-bin/timer.pl) as response: for line in response: line = line.decode(utf-8) # Decoding the binary data to text. if EST in line or EDT in line: # look for Eastern Time print(line)smtplib 发送邮件
import smtplib server = smtplib.SMTP(localhost) server.sendmail(soothsayer@example.org, jcaesar@example.org, """To: jcaesar@example.org From: soothsayer@example.org Beware the Ides of March. server.quit()
(注意: 这个例子需要localhost运行一个邮件服务)
日期和时间datetime 提供了可以通过简单或复杂方式处理日期和时间的类,在提供日期时间运算的同时,侧重于高效的为格式化输出和处理进行成员导出,也支持时区相关的对象.
# dates are easily constructed and formatted from datetime import date now = date.today() now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")(zlib,
gzip,
bz2,
lzma,
zipfile,
tarfile)等模块支持常见的文件归档和压缩格式import zlib s = bwitch which has which witches wrist watch len(s) t = zlib.compress(s) len(t) zlib.decompress(t) zlib.crc32(s)一些Python用户对了解解决同一问题的不同解决方式的实际性能有着很深的兴趣,Python为直接地这些问题提供了测量工具。
例如:直接使用tuple装包和开包特性替代传统的参数交换方式是很有吸引力的,timeit 快速示范了一定程度上的性能优势。
from timeit import Timer Timer( t=a; a=b; b=t , a=1; b=2 ).timeit() Timer( a,b = b,a , a=1; b=2 ).timeit()与timeit的细粒度相反,profile和pstats 提供了可以识别大块代码时间临界的工具.
开发高质量的软件的一种方法是在开发软件的过程中为每个function编写测试,并在开发过程中频繁的运行这些测试.
doctest 提供可以扫描并验证通过程序文档注入的测试.测试的构建和剪切粘贴一个调用和结果到文档中一样简单,它通过提供给用户一个例子和一个文档测试来确保代码和文档的一致性来改善文档。
def average(values): """Computes the arithmetic mean of a list of numbers. print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) import doctest doctest.testmod() # automatically validate the embedded testsunittest没有doctest 那么简洁易用,但是它允许在一个单独的测试文件中维护更为复杂的测试集
import unittest class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) with self.assertRaises(ZeroDivisionError): average([]) with self.assertRaises(TypeError): average(20, 30, 70) unittest.main() # Calling from the command line invokes all testsPython有一个’内置电池’理念,它能很好地通过一些成熟并且健壮的package表现出来。例如:
xmlrpc.client和xmlrpc.server 将远程程序调用实现成了简单的任务,尽管叫这个名字,但不需直接了解或处理xml。 emailpackage是一个负责管理邮件消息的库,包含MIME和其他RFC2822-base消息文件,不像smtplib和piplib一样真正的进行消息收发,email package有一个复杂工具集来构建或解码复杂消息结构(包括附件)及实现网络编码和报头协议 json为解析这种流行的数据交换格式提供了强大的支持,csv支持以逗号进行分隔值的形式进行文件的读写,通常支持数据库和电子表格,xml.etree.ElementTree, xml.dom 和 xml.sax对xml程序提供支持,这些package极大地简化了Python和其他工具间的数据交换。 sqlite3是对SQLite数据库库的包装,提供了一个持久性数据库,可以使用稍微不标准SQL语法对数据库进行更新和访问。 国际化由gettextlocal和codecs等package提供支持
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/62237.html
apple