设为首页 收藏本站
查看: 976|回复: 0

[经验分享] 「学习笔记——Python」Python标准库简明教程

[复制链接]

尚未签到

发表于 2015-4-24 10:35:52 | 显示全部楼层 |阅读模式
10 Python标准库简明教程



Table of Contents




  • 1 操作系统接口
  • 2 文件通配符
  • 3 命令行参数
  • 4 错误输出重定向和程序终止
  • 5 字符串模式匹配
  • 6 数学
  • 7 Internet访问
  • 8 日期和时间
  • 9 数据压缩
  • 10 性能测量
  • 11 质量控制



1 操作系统接口


  os 模块提供了一系列与系统交互的模块:

>>> os.getcwd()  # Return the current working directory
'/home/minix/Documents/Note/Programming/python/lib1'
>>> os.chdir('~/python') # Change current working directory
Traceback (most recent call last):
File "", line 1, in
OSError: [Errno 2] No such file or directory: '~/python'
>>> os.chdir('/home/minix/python') # Change current working directory
>>> os.system('mkdir tos')
0
>>> os.system('ls')
classes        errorAexception       learnPython  pythonInterpreter
controlFlow    informalIntroduction  lib1         tos
dataStructure  io                    modules
0

  注意


  • 注意使用 import os, 而非 from os import *.否则os.open()会覆盖内置的open()函数
  • 路径要写全路径哦~
  shutil 模块提供了易于使用的接口,方便我们日常的文件管理工作

>>> os.system('touch data.db')
0
>>> os.system('ls')
data.db
0
>>> import shutil
>>> shutil.copy('data.db', 'archive.db')
>>> os.system('ls')
archive.db  data.db
0



2 文件通配符


  glob 模块提供了使用通配符获取文件名列表的方式:

>>> os.system ('ls')
archive.db  data.db  foo.cpp
0
>>> import glob
>>> glob.glob('*.db')
['archive.db', 'data.db']



3 命令行参数


  通常使用脚本时会给它提供参数,通过sys模块的argv属性可以得到这些参数

#demo.py
import sys
print sys.argv

  这样,在命令行执行时会得到:

$ python demo.py one two three
['demo.py', 'one', 'two', 'three']

  geropt 模块使用 Unix的 getopt()函数的方式处理sys.argv. 更多强大灵活的命令行处理方式可以在 argparse 模块中找到。



4 错误输出重定向和程序终止


  sys 模块还提供了三个属性:stdin,stdout,和stderr.当stdout被重定向时,stderr可以显示错误和警告.

>>> import sys
>>> sys.stderr.write('Warning, long file not found\n')
Warning, long file not found

  结束一个脚本最直接的方式是使用 sys.exit()



5 字符串模式匹配


  re 模块为高级字符串处理提供了正则表达式工具.对一些复杂的匹配的操作,正则表达式通常能提供 最优的解决方案:

>>> re.sub(r'(\b[a-z]+) \l', r'\l', 'cat in the the hat hat')
'cat in the the hat hat'

  当只需要一些简单的功能时,string 方法是最好的,因为它们容易阅读和调试

>>> 'tea for too'.replace('too', 'two')
'tea for two'



6 数学


  math 模块提供了访问底层C函数库中浮点处理函数的功能:

>>> import math
>>> math.cos(math.pi / 4.0)
0.7071067811865476
>>> math.log(1024, 2)
10.0

  random 模块提供了用于随机选择的工具

>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'banana'
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(xrange(100), 10)
[37, 22, 82, 76, 51, 58, 33, 92, 56, 48]
>>> random.sample(xrange(100), 10)
[13, 44, 15, 70, 69, 42, 17, 0, 14, 81]
>>> random.random()
0.4976690748939975
>>> random.random()
0.10626734770387691
>>> random.randrange(10)
6
>>> random.randrange(10)
9



7 Internet访问


  python中有一系列模块用于访问internet,处理internet协议.其中最简单的是urllib2和smtplib,前者用于从URL接收数据, 后者可以发送邮件.



8 日期和时间


  datatime 模块提供了处理日期和时间的一系列类,从简单到复杂.

>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2013, 3, 7)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'03-07-13. 07 Mar 2013 is a Thursday on the 07 day of March.'
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
17751



9 数据压缩


  常见的数据打包和压缩格式,在python中都得到直接支持,它们在下列模块中:zlib,gzip,bz2,zipfile和tarfile.

>>> import zlib
>>> str = "we repeat repeat and repeat many time"
>>> len(str)
37
>>> t = zlib.compress(str)
>>> len(t)
32
>>> zlib.decompress(t)
'we repeat repeat and repeat many time'



10 性能测量


  有些python用户需要比较解决同一问题时,不同方法的性能优劣.Python提供了相应的度量工具,可以快速得出结论.

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.05308699607849121
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.042800188064575195

  与timeit相比,profile和pstat模块提供了一系列工具,用于识别大段代码中的关键区域的时间.



11 质量控制


  开发高质量软件的一种方式是,在开发的过程为每一个函数编写测试程序,并多次运行它们. doctest 模块提供了一个工具,用于扫描一个模块,验证嵌入在程序 docstring 中的测试. 嵌入的测试代码结构非常简单,就像把输出的结果复制粘贴到测试代码后一样.

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+1)
import doctest
doctest.testmod()

  unittest 模块可不像 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)
self.assertRaises(ZeroDivisionError, average, [])
self.assertRaises(TypeError, average, 20, 30, 70)
unittest.main() # Calling from the command line invokes all tests




原文链接:http://docs.python.org/2/tutorial/stdlib.html

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-60233-1-1.html 上篇帖子: python自定义函数在Python解释器中调用 下篇帖子: Python的学习(二十一)----Python的静态变量
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表