import os
print(os.getcwd())#get current path and print it
import glob
print(glob.glob('py3*')#return a list of file which format are py in the current work space
‘/Users/zl/Documents/pythonLearn/python3’
import sys
print(sys.argv)
['demo.py', 'one', 'two', 'three']
[’’]
sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
47
re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
[‘foot’, ‘fell’, ‘fastest’]
re.findall(r'\bh[a-z]*', 'which foot or hand fell fastest')
[‘hand’]
import math
math.cos(math.pi/4)
0.7071067811865476
math.log(1024, 2)
10.0
随机数生成工具
import random
random.choice(random.choice(['apple', 'pear', 'banana'])
sampling(range(x), n)为无重复生成n个(0,x)之间数字。
random.sample(range(100), 10)# sampling without replacement
[54, 72, 65, 92, 21, 75, 7, 51, 8, 88]
random.random()# random float
.07998797562772264
random.randrange(6)#random integer chosen from range(6)
4
有几个模块用于访问互联网以及处理网络通信协议,其中最简单的两个是用于处理从url接收的数据的urllib.request以及用于发送电子邮件的smtplib:
>>> from urllib.request import urlopen
>>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
... 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)
Nov. 25, 09:43:32 PM EST
>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('[email protected]', '[email protected]',
... """To: [email protected]
... From: [email protected]
...
... Beware the Ides of March.
... """)
>>> server.quit()
datetime 模块为日期和时间处理同事提供了简单和复杂的方法。
支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。该模块也支持时区处理。
#!/usr/bin/python3
# coding=utf-8
import datetime
from datetime import date
now = date.today()# current time
print(now)
print(now.strftime("%m-%d-%y.%d %b %Y is a %A on the %d day of %B."))# calculate some other information
birthday = date(1964, 7, 31)
age = now-birthday
print(age.days)#birthday
输出结果
2019-07-24
07-24-19.24 Jul 2019 is a Wednesday on the 24 day of July.
20081
以下模块直接支持通用的数据打包格式和压缩格式,zlib、gzip、bz2、zipfile以及tarfile。
#!/usr/bin/python3
# coding=utf-8
import zlib
s = b'witch which has which withches wrist watch'
print(len(s))
t = zlib.compress(s)
print(len(t))
输出结果
42
41
衡量同一问题的不同解决方法之间的性能差异。
#!/usr/bin/python3
# coding=utf-8
from timeit import Timer
t1 = Timer('t=a;a=b;b=t','a=1;b=2').timeit()#传统方法交换元素
t2 = Timer('a, b = b, a', 'a=1;b=2').timeit()#元组封装和拆封来交换元素
print("t1= %f, t2= %f"%(t1,t2))
输出结果
t1= 0.019668, t2= 0.016124
相对于timeit的细粒度,:mod:profile和pstats模块提供了针对更大代码块的时间度量工具。
为每一个函数开发测试代码,并在开发过程中经常测试。
doctest模块提供了一个工具,扫描模块并根据程序中内嵌的文档字符串执行测试。测试构造如同简单的将他的输出结果剪切并粘贴到文档字符串中。
通过用户提供的例子,它强化了文档,允许doctest模块确认代码的结果是否与文档一致:
正确例子
#!/usr/bin/python3
# coding=utf-8
import doctest
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40
"""
return sum(values) / len(values)
print(doctest.testmod()) # 自动验证嵌入测试
TestResults(failed=0, attempted=1)
错误例子
将输出结果改为正确结果以外的值即可查看错误的输出
#!/usr/bin/python3
# coding=utf-8
import doctest
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
100
"""
return sum(values) / len(values)
print(doctest.testmod()) # 自动验证嵌入测试
输出结果
File “py3stdlib.py”, line 6, in main.average
Failed example:
print(average([20, 30, 70]))
Expected:
100
Got:
40
1 items had failures:
1 of 1 in main.average
Test Failed 1 failures.
TestResults(failed=1, attempted=1)
如上所述输出结果所示,我们所希望的输出结果Expected是100,但是实际上Got的是40,总共尝试的attemped是1个,失败failure了1个。
这个模块不如doctest容易上手,但是他可以在一个独立的文件里面提供更全面的测试集:
#!/usr/bin/python3
# coding=utf-8
import unittest
import 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)
print(doctest.testmod()) # 自动验证嵌入测试
class TestStatisticalFunctions(unittest.TestCase):
def test_average(self):
self.assertEqual(average([20, 30, 70]), 40)
self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
self.assertRaises(ZeroDivisionError, average, [])
self.assertRaises(TypeError, average, 20, 30, 70)
print(unittest.main()) # Calling from the command line invokes all tests
.----------------------------------------------------------------------
Ran 1 test in 0.000s
OK