python3基础-os模块&异常&面向对象&标准库
一. OS 文件/目录方法
os 模块提供了非常丰富的方法用来处理文件和目录,能够完成shell命令的工作
os.access(path, mode);
模式
- os.F_OK 作为access()的mode参数,测试path是否存在。
- os.R_OK 包含在access()的mode参数中 , 测试path是否可读。
- os.W_OK 包含在access()的mode参数中 , 测试path是否可读。
- os.X_OK 包含在access()的mode参数中 ,测试path是否可执行。
os.chdir(path)					#改变当前工作目录
os.chflags(path, flags)			#设置路径的标记为数字标记
flags -- 可以是以下值:
- stat.UF_NODUMP: 非转储文件
- stat.UF_IMMUTABLE: 文件是只读的
- stat.UF_APPEND: 文件只能追加内容
- stat.UF_NOUNLINK: 文件不可删除
- stat.UF_OPAQUE: 目录不透明,需要通过联合堆栈查看
- stat.SF_ARCHIVED: 可存档文件(超级用户可设)
- stat.SF_IMMUTABLE: 文件是只读的(超级用户可设)
- stat.SF_APPEND: 文件只能追加内容(超级用户可设)
- stat.SF_NOUNLINK: 文件不可删除(超级用户可设)
- stat.SF_SNAPSHOT: 快照文件(超级用户可设)
os.chmod(path, mode)			#更改权限
os.chown(path, uid, gid)		#改变文件所有者
os.chroot(path)					#改变当前进程目录
os.close(fd)					#关闭文件描述符
os.closerange(fd_low, fd_high)	#关闭所有文件描述符,从 fd_low (包含) 到 fd_high (不包含), 错误会忽略
os.dup(fd)						#赋值文件描述符
os.dup2(fd, fd2)				#将一个文件描述符 fd 复制到另一个 fd2
os.fchdir(fd)					#通过文件描述符改变当前工作目录
os.fchmod(fd, mode)				#改变一个文件的访问权限,该文件由参数fd指定,参数mode是Unix下的文件访问权限
os.fchown(fd, uid, gid)			#修改一个文件的所有权,这个函数修改一个文件的用户ID和用户组ID,该文件由文件描述符fd指定。
os.fdatasync(fd)				#强制将文件写入磁盘,该文件由文件描述符fd指定,但是不强制更新文件的状态信息。
os.fdopen(fd[, mode[, bufsize]])#通过文件描述符 fd 创建一个文件对象,并返回这个文件对象
os.fpathconf(fd, name)			#返回一个打开的文件的系统配置信息。
os.fstat(fd)					#返回文件描述符fd的状态,像stat()。
os.fstatvfs(fd)					#返回包含文件描述符fd的文件的文件系统的信息,像 statvfs()
os.fsync(fd)					#强制将文件描述符为fd的文件写入硬盘。
os.ftruncate(fd, length)		#裁剪文件描述符fd对应的文件, 所以它最大不能超过文件大小
os.getcwd()						#返回当前工作目录
os.getcwdu()					#返回一个当前工作目录的Unicode对象
os.isatty(fd)					#如果文件描述符fd是打开的,同时与tty(-like)设备相连,则返回true, 否则False。
os.removedirs(path)				#递归删除目录
os.rename(src, dst)	   			#重命名文件或目录
os.renames(old, new)			#递归对目录更名
os.rmdir(path)					#删除目录,如果非空抛异常OSError
os.stat(path)					#获取path指定的路径信息
os.stat_float_times([newvalue])	#决定stat_result是否以float对象显示时间戳
os.statvfs(path)				#获取指定路径的文件系统统计信息
os.symlink(src, dst)			#创建一个软连接
os.tcgetpgrp(fd)				#返回与终端fd关联的进程组
http://www.runoob.com/python3/python3-os-file-methods.html
## 二. 异常 **捕获异常** try的最后有一个可选的else
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
else:
    print(arg, 'has', len(f.readlines()), 'lines')
    f.close()
抛出异常
raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类)
raise NameError('HiThere')
自定义异常
创建一个新的exception类来拥有自己的异常。异常应该继承自 Exception 类,或者直接继承,或者间接继承
例子:
class MyError(Exception):
	def __init__(self, value):
	    self.value = value
	def __str__(self):
	    return repr(self.value)
## 三. 面向对象 **类对象** 类对象支持两种操作:属性引用和实例化
class MyClass:
    """一个简单的类实例"""
    i = 12345
    def f(self):
        return 'hello world'
# 实例化类
x = MyClass()
# 访问类的属性和方法
print("MyClass 类的属性 i 为:", x.i)
print("MyClass 类的方法 f 输出为:", x.f())
类变量
类变量可以不显示的指定,可以直接定义
class people:
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s 说: 我 %d 岁。" %(self.name,self.age))
构造方法
类的方法,都需要加self
class Complex:
	def __init__(self, realpart, imagpart):
		self.r = realpart
		self.i = imagpart
多继承
需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,python从左至右搜索 即方法在子类中未找到时,从左到右查找父类中是否包含方法。
class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>
方法重写
#!/usr/bin/python3
class Parent:        # 定义父类
   def myMethod(self):
      print ('调用父类方法')
class Child(Parent): # 定义子类
   def myMethod(self):
      print ('调用子类方法')
c = Child()          # 子类实例
c.myMethod()         # 子类调用重写方法
类属性与方法
私有变量和私有方法在前面加__
class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0    # 公开变量
    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print (self.__secretCount)
        
    def __private_method(self):
        print("private method")
类的私有方法
__init__ : 构造函数,在生成对象时调用
__del__ : 析构函数,释放对象时使用
__repr__ : 打印,转换
__setitem__ : 按照索引赋值
__getitem__: 按照索引获取值
__len__: 获得长度
__cmp__: 比较运算
__call__: 函数调用
__add__: 加运算
__sub__: 减运算
__mul__: 乘运算
__div__: 除运算
__mod__: 求余运算
__pow__: 称方
运算符重载
#!/usr/bin/python3
class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b
   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)
   
   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
## 四. 标准库 **操作系统接口** 建议使用 "import os" 风格而非 "from os import *" os是个大型包,内置的dir()和help()非常有用
dir(os)
help(os)
针对日常文件和目录管理任务,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']
命令行参数
调用py脚本传入的参数,以链表形式存储于 sys 模块的 argv 变量
demo.py one two three
>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']
错误输出重定向和程序终止
sys 还有 stdin,stdout 和 stderr 属性
sys.stderr.write('Warning, log file not found starting a new one\n')
字符串正则匹配
简单功能使用字符串的方法
>>> 'tea for too'.replace('too', 'two')
'tea for two'
复杂功能使用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'
数学
math模块提供了底层的c库访问
>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0
random模块提供了随机函数工具
>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # random float
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4
网络
有几个模块用于网络,最简单的两个
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)
<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
>>> # dates are easily constructed and formatted
>>> 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.'
>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368
数据压缩
以下模块直接支持通用的数据打包和压缩格式:zlib,gzip,bz2,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)
226805979
性能度量
有些用户对了解解决同一问题的不同方法之间的性能差异很感兴趣。Python 提供了一个度量工具,timeit
>>> 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 的细粒度,:mod: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) / len(values)
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
 
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号