python标准库-第一部分
来源:互联网 发布:vscode 切换大小写 编辑:程序博客网 时间:2024/06/01 09:05
本文译自https://docs.python.org/2.7/tutorial/。完全是出于个人兴趣翻译的,请勿追究责任。另外,谢绝商业牟利。刊印请与本人和原作者联系,无授权不得刊印,违者必究其责任。如需转发,请注明来源,并保留此行,尊重本人的劳动成果,谢谢。
来源:CSDN博客
作者:奔跑的QQEE
python 版本:2.7.13
(本文有删改)
python标准库-第一部分
一、操作系统接口
os
模块为与操作系统交互提供了许多方法。例:
>>> import os>>> os.getcwd() # 返回当前工作目录'C:\\Python26'>>> os.chdir('/server/accesslogs') # 改变当前工作目录>>> os.system('mkdir today') # R运行命令 mkdir0
使用import os
而不要使用from os import *
。这样在执行open()
方法时可以保证调用的是os.open()
方法而不是内置的open()
方法。这两种方法作用完全不同。os.open(file,flags[,mode])
是打开文件并根据其提供的flags设置对应的flags,根据提供的mode设置对应的mode
。open(name[,mode[,buffering]])
是打开文件并返回文件对象
。
使用os
模块时,掌握如何使用内置的dir()
和help()
方法是十分必要的。如此使用,例:
>>> import os>>> dir(os)<returns a list of all module functions>>>> help(os)<returns an extensive manual page created from the module's docstrings>
为便于目录管理,系统提供了shutil
模块。如此使用:
>>> import shutil>>> shutil.copyfile('data.db', 'archive.db') # 复制文件到新文件>>> shutil.move('/build/executables', 'installdir') # 移动文件到新目录
二、文件通配符
glob
模块提供了使用通配符查找文件列表的方法。例:
>>> import glob>>> glob.glob('*.py')['primes.py', 'random.py', 'quote.py']
三、命令行参数
经常需要处理命令行参数。这些参数以列表的形式存储在sys
模块的argv
属性中。下例结果是在命令行中执行完python demo.py one two three
后得到的:
>>> import sys>>> print sys.argv['demo.py', 'one', 'two', 'three']
getopt
模块处理sys.argv
是通过使用unix系统的getopt()
方法。argparse
模块提供了更为强大灵活的命令行处理方法。
四、错误结果输出与终端操作
sys
模块有三个属性:stdin,stdout,stderr
。当 stdout
被定向时,可以用stderr
输出错误提示。例:
>>> sys.stderr.write('Warning, log file not found starting a new one\n')Warning, log file not found starting a new one
一种直接的操作终端方法是:sys.exit()
。
五、字符串样式匹配
re
模块提供了正则表达式以便字符串处理。例:
>>> import re>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')['foot', 'fell', 'fastest']>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')'cat in the hat'
若是仅需简单的字符串处理,调用字符串函数更合适(更便于阅读,代码调试)。而不必使用正则表达式。例:
>>> 'tea for too'.replace('too', 'two')'tea for two'
六、数学处理
math
模块提供了调用底层C语言中浮点运算的方法。
>>> import math>>> math.cos(math.pi / 4.0)0.70710678118654757>>> math.log(1024, 2)10.0
random
模块提供了产生随机的方法。
>>> import random>>> random.choice(['apple', 'pear', 'banana'])'apple'>>> random.sample(xrange(100), 10) # 不放回抽样[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]>>> random.random() # 随机浮点数0.17970987693706186>>> random.randrange(6) # [0,6) 范围内产生随机整数4
七、网络接口
python中有很多访问互联网,处理网络协议的模块。有两个最简单的模块:urllib2,smtplib
。
urllib2
用来检索指定URL代表的位置中的数据。smtplib
用来发送邮件。例:
>>> import urllib2>>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):... if 'EST' in line or 'EDT' in line: # 查找东部时间... print line<BR>Nov. 25, 09:43:32 PM EST>>> 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()
八、日期时间
datetime
模块提供了操作时间日期的类;有简单的操作方式,也有复杂的。用例如下:
>>> from datetime import date>>> now = date.today()>>> nowdatetime.date(2003, 12, 2)>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'>>> # 支持日期计算>>> birthday = date(1964, 7, 31)>>> age = now - birthday>>> age.days14368
九、数据压缩
python支持一般的压缩数据格式。不同模块实现不同压缩格式,如zlib
,gzip
,bz2
,zipfile
,tarfile
。例:
>>> import zlib>>> s = 'witch which has which witches wrist watch'>>> len(s)41>>> t = zlib.compress(s)>>> len(t)37>>> zlib.decompress(t)'witch which has which witches wrist watch'>>> zlib.crc32(s)226805979
十、性能测定
python提供了用于测定性能的工具。例:
>>> from timeit import Timer>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()0.57535828626024577>>> Timer('a,b = b,a', 'a=1; b=2').timeit()0.54962537085770791
与timeit
模块类似的还有profile
模块,pstats
模块。不过后两者用于测定大块代码段中关键部分代码的性能。
十一、质量控制
保证开发出高质量软件的方法之一是测试
。这一方法要在开发过程中反复实行。
doctest
模块提供了检测程序中文本字符的方法。例:
>>>def average(values):... """Computes the arithmetic mean of a list of numbers....... >>> print average([20, 30, 70])... 40.0... """... return sum(values, 0.0) / len(values)>>>import doctest>>>doctest.testmod() TestResults(failed=0, attempted=1) # 测试的结果
unittest
模块支持更为全面的测试。例:
import unittestclass 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() ----------------------------------------------------------------------Ran 0 tests in 0.000sOK
- python标准库-第一部分
- 第一部分 2.标准库类型
- Python 第一部分 起步
- 第一部分 基本语言 第三章 标准库类型(3.2标准库string类型)
- 第一部分 基本语言 第三章 标准库类型(3.3标准库vector类型)
- 第一部分 基本语言 第三章 标准库类型(3.5标准bitset类型)
- STL标准程序库第一部分总结(Auto_ptr&&numeric_limits,标准模板库,迭代器的配接器)
- Python标准库07 信号 (signal包,部分os包)
- Python标准库09 当前进程信息 (部分os包)
- Python标准库07 信号 (signal包,部分os包)
- Python标准库07 信号 (signal包,部分os包)
- Python信号标准库(signal包,部分os包)
- Python标准库07 信号 (signal包,部分os包)
- 第一部分 基本语言 第三章 标准库类型(命名空间的using声明)
- 第一部分 基本语言 第三章 标准库类型(3.4迭代器简介)
- Python十日谈:第一日-标准类型
- XSLT 1.0推荐标准摘译(第一部分)
- XPATH 1.0推荐标准摘译(第一部分)
- 关于方法的重载和重写的区别
- java术语(PO/POJO/VO/BO/DAO/DTO)
- C语言系列之C语言如何返回字符串数组
- iOS 中 static 的作用和内存划分
- redis缓存的使用总结
- python标准库-第一部分
- TCP的三次握手(建立连接)和四次挥手(关闭连接)
- java计算两个日期之间有多少天
- Python(2) Python 模块帮助文档查询
- final关键字
- python语法简单入门
- Ubuntu16.04+cuda8.0+cudnn6.0+tensorflow(一)
- GetSymbolicLinkDeviceName
- win7 chrome Regex Search 插件 正则表达式搜索