A Byte of Python 笔记(12)python 标准库:sys、os,更多内容

第14章 python 标准库

Python标准库是随Python附带安装的,它包含大量极其有用的模块。

sys 模块

sys 模块包含系统对应的功能。如 sys.argv 列表包含命令行参数。

# -*- coding: utf-8 -*-
# Filename: cat.py

import sys

def readfile(filename):
    '''print a file to the standard output.'''
    f = file(filename)
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print line, # notice comma
    f.close()

# script starts from here
if len(sys.argv) < 2:
    print 'No action specified.'
    sys.exit()

if sys.argv[1].startswith('--'):
    option = sys.argv[1][2:]
    # fetch sys.argv[1] but without the first two characters
    if option == 'version':
        print 'Version 1.2'
    elif option == 'help':
        print '''
        This program prints files to the standard output.
        Any number of files can be specified.
        Options include:
        --version : prints the version number
        --help    : display this help'''
    else:
        print 'Unknown option.'
    sys.exit()
else:
    for filename in sys.argv[1:]:
        readfile(filename)

image

os 模块

该模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行。一个例子就是使用 os.sep 可以取代操作系统特定的路径分割符。

下面列出了一些在os模块中比较有用的部分。

  • os.name 字符串指示你正在使用的平台。比如对于 Windows,它是 'nt',而对于 Linux/Unix 用户,它是 'posix'。
  • os.getcwd() 函数得到当前工作目录,即当前Python脚本工作的目录路径。
  • os.getenv() 和 os.putenv() 函数分别用来读取和设置环境变量。
  • os.listdir() 返回指定目录下的所有文件和目录名。
  • os.remove() 函数用来删除一个文件。
  • os.system() 函数用来运行 shell 命令。
  • os.linesep字符串给出当前平台使用的行终止符。例如,Windows 使用 ' ',Linux 使用 ' ' 而 Mac 使用 ' '。
  • os.path.split() 函数返回一个路径的目录名和文件名。
>>> os.path.split('/home/swaroop/byte/code/poem.txt')('/home/swaroop/byte/code', 'poem.txt')
  • os.path.isfile() 和 os.path.isdir() 函数分别检验给出的路径是一个文件还是目录。类似地,os.path.existe() 函数用来检验给出的路径是否真地存在。

 

第15章 更多python内容

特殊方法

在类中有一些特殊的方法具有特殊的意义,比如 __init__ 和 __del__ 方法。特殊的方法都被用来模仿某个行为。例如,如果你想要为你的类使用 x[key] 这样的索引操作(就像列表和元组一样),那么你只需要实现 __getitem__() 方法就可以了。

名称

说明

__init__(self,...)

这个方法在新建对象要被返回使用之前被调用。

__del__(self)

在对象要被删除之前调用。

__str__(self)

在我们对对象使用 print 语句或是使用 str()的时候调用。

__lt__(self,other)

当使用 小于 运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法。

__getitem__(self,key)

使用 x[key]索引操作符的时候调用。

__len__(self)

对序列对象使用内建的 len()函数的时候调用。

单语句块

每一个语句块是通过缩进层次与其它块区分开来。但如果语句块只包含一个语句,可以在条件语句或循环与语句的同一行指明它。

>>> flag = True
>>> if flag: print 'Yes'
...
Yes

单个语句被直接使用而不是作为一个独立的块使用。虽然这样做可以使你的程序变得 小一些 ,但是除了检验错误之外不建议使用这种缩略方法。

列表综合

通过列表综合,可以从一个已有的列表导出一个新的列表。

# -*- coding: utf-8 -*-
# Filename: list_comprehension.py

listone = [2,3,4]
listtwo = [2*i for i in listone if i>2]
print listtwo

image

我们为满足条件(if i > 2)的数指定了一个操作(2*i),从而导出一个新的列表。

在函数中接收元组和列表

当要使函数接收元组或字典形式的参数的时候,有一种特殊的方法,它分别使用*和**前缀。这种方法在函数需要获取可变数量的参数的时候特别有用。

>>> def powersum(power, *args):
...     '''Return the sum of each argument raised to specified power.'''
...     total = 0
...     for i in args:
...         total += pow(i, power) # pow(i,power)=i**power
...     return total
...
>>> powersum(2,3,4) # power=2,args=(3,4)
25 # 3**2 + 4**2
>>> powersum(2,10) # power=2,args=(10,)
100 # 10**2

由于在 args 变量前有*前缀,所有多余的函数参数都会作为一个元组存储在 args 中。如果使用的是 ** 前缀,多余的参数则会被认为是一个字典的键/值对。

lambda形式

lambda语句被用来创建新的函数对象,并且在运行时返回它们。

# -*- coding: utf-8 -*-
# Filename: lambda.py

def make_repeater(n):
    return lambda s: s*n

twice = make_repeater(2)

print twice('word')
print twice(5)

image

make_repeater 函数在运行时创建新的函数对象,并且返回它。lambda 语句用来创建函数对象。本质上,lambda 需要一个参数,后面仅跟单个表达式作为函数体,而表达式的值被这个新的函数返回。

注意,即便是 print 语句也不能用在 lambda 形式中,只能使用表达式。

exec 和 eval 语句

exec 语句用来执行储存在字符串或文件中的 python 语句。如,可以在运行时生成一个包含 python 代码的字符串,然后使用 exec 语句执行。

>>> exec 'print"Hello World"'
Hello World

eval 语句用来计算存储在字符串中的有效 python 表达式。

>>> eval('2*3')
6

assert 语句

assert 语句用来声明某个条件是真的。如,如果你非常确信某个列表中至少有一个元素,而你想要检验这一点,并在它非真的时候引发一个错误,那么 assert 语句是应用在这种情况下的理想语句。当 assert 语句失败时,引发 AssertionError。

>>> mylist = ['item']
>>> assert len(mylist) >= 1
>>> mylist.pop()
'item'
>>> assert len(mylist) >= 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

repr 函数

repr 函数用来取得对象的规范字符串表示。反引号(转换符)可以完成相同的功能。

注意,大多数时候 eval(repr(object)) == object

>>> i = []
>>> i.append('item')
>>> `i`
"['item']"
>>> repr(i)
"['item']"

基本上,repr 函数和反引号用来获取对象的可打印的表示形式。可以通过定义的 __repr__ 方法来控制你的对象在被 repr 函数调用的时候返回的内容。

原文地址:https://www.cnblogs.com/blueskylcc/p/5364605.html