zoukankan      html  css  js  c++  java
  • [学习笔记] Python标准库简明教程 [转]

    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 "<stdin>", line 1, in <module>
    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
    ')
    Warning, long file not found
    

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

    5 字符串模式匹配

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

    >>> re.sub(r'([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
  • 相关阅读:
    Java实现 计蒜客 拯救行动
    Java实现 计蒜客 拯救行动
    Java实现 LeetCode 174 地下城游戏
    Java实现 LeetCode 174 地下城游戏
    Java实现 LeetCode 174 地下城游戏
    Java实现 LeetCode 173 二叉搜索树迭代器
    Java实现 LeetCode 173 二叉搜索树迭代器
    Visual Studio的SDK配置
    怎样使用CMenu类
    mfc menu用法一
  • 原文地址:https://www.cnblogs.com/Felixdh/p/3818108.html
Copyright © 2011-2022 走看看