python 一些基本库 I

python 一些基本库 I


1 系统操作 os

    
    >>> import os
    
    
    >>> os.getcwd()      # Return the current working directory
        'C:\\Python37'
    >>> os.chdir('/server/accesslogs')   # Change current working directory
    
    >>> os.system('mkdir today')   # Run the command mkdir in the system shell

2 文件操作 shutils


    >>> import shutil
    >>> shutil.copyfile('data.db', 'archive.db') 拷贝文件
        'archive.db'
    >>> shutil.move('/build/executables', 'installdir') 移动重命名
        'installdir'

3 查找文件 glob


    import glob
    
    glob.glob("*.go")
    
    ['server.go', 'server1.go']

4 输入输出 sys



1 sys.argv  获取参数

    python demo.py one two
    
    demo.py
    
        import sys
        print(sys.argv)
        >> ['demo.py', 'one', 'two', 'three']


2  sys.stderr

    sys.stderr.write('Warning, log file not found starting a new one\n')
    没有\n 不会输出

5 数学统计相关 math, random, statistic


1 math 
    
    math.cos(math.pi / 4)
    math.log(1024, 2)
    

2 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)


3  statistics

    import statistics
    
    >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
    
    >>> statistics.mean(data)
    1.6071428571428572
    
    >>> statistics.median(data)
    1.25
    
    >>> statistics.variance(data)
    1.3720238095238095


6 internet 相关 urllib, smtplib


1  urllib
    
    >>> 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)


2  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()


7 时间日期相关 datetime, time

 
from datetime import date

now = date.today()

>>> now #  datetime.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.days
    14368
 
 

8 文件压缩 zlib, gzip, bz2, lzma, zipfile, tarfile


    >>> import zlib
    
    >>> s = b'witch which has which witches wrist watch'
    >>> len(s)
    41
    
    >>> t = zlib.compress(s)  压缩
    >>> len(t)
    37
    
    >>> zlib.decompress(t)     解压缩
    b'witch which has which witches wrist watch'
    
    
    >>> zlib.crc32(s)       CRC校验
    226805979

9 性能检测 timeit, profile, pstats

    
    
1 timeit  # Measure execution time of small code snippets


    >>> from timeit import Timer
    
    
    In [17]: Timer("t=a;  a=b; b=t", "a=1; b=2").timeit()
    Out[17]: 0.03515957900003741
    
    In [18]: Timer("a, b= b, a", "a=1; b=2").timeit()
    Out[18]: 0.019163364000064576


2 profile

 import profile

 def test():
    ...:     for i in range(10):
    ...:         print(i*i)

 profile.run("test()", 'test.log' )


  >>> 

   15 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 :0(exec)
       10    0.000    0.000    0.000    0.000 :0(print)
        1    0.000    0.000    0.000    0.000 :0(setprofile)
        1    0.000    0.000    0.000    0.000 <ipython-input-19-67b408abaa61>:1(test)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        0    0.000             0.000          profile:0(profiler)
        1    0.000    0.000    0.000    0.000 profile:0(test())



    ncalls表示函数调用的次数
    
    tottime表示指定函数的总的运行时间除掉函数中调用子函数的运行时间
    
    percall:(第一个 percall等于 tottime/ncalls
    
    cumtime表示该函数及其所有子函数的调用运行的时间即函数开始调用到返回的时间
    
    percall:(第二个 percall即函数运行一次的平均时间等于 cumtime/ncalls
    
    filename:lineno(function)每个函数调用的具体信息



3  pstats


    实例化对象

    p = pstats.Stats("test.out")  根据profile之前生成的 分析文件

        # strip_dirs(): 去掉无关的路径信息
        # sort_stats(): 排序,支持的方式和上述的一致
        # print_stats(): 打印分析结果,可以指定打印前几行

    # 按照函数名排序,只打印前3行函数的信息, 参数还可为小数,表示前百分之几的函数信息
        p.strip_dirs().sort_stats("name").print_stats(3)

    # 按照运行时间和函数名进行排序
     p.strip_dirs().sort_stats("cumulative", "name").print_stats(0.8)

    # 如果想知道有哪些函数调用了test
        p.print_callers("test")

    # 查看test()函数中调用了哪些函数
         p.print_callees("test")

10 代码检测 doctest, unittest


1 doctest 

    doctest.txt
        
        >>> from math import gcd
        >>> gcd(3,6)
        3   预期的结果
        >>> gcd(12,6)
        6

          
    
    >> python -m doctest -v doctest.txt   -m 指定模块 -v 表示输出信息
    
        
        Trying:
            from math import gcd
        Expecting nothing
        ok
        Trying:
            gcd(3,6)
        Expecting:
            3
        ok
        Trying:
            gcd(12,6)
        Expecting:
            6
        ok
        1 items passed all tests:
           3 tests in doctest.txt
        3 tests in 1 items.
        3 passed and 0 failed.
        Test passed.



    

2  unittest

    import unittest
    
    
    def average(values):
       ...:     return sum(values) / len(values)
    
    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 tests


Buy me a 肥仔水!