usually advised to quote command in its entirety with single quotes.
Some Python modules as scripts: python -m module [arg] ...
退出
Typing an end-of-file character (Control-D on Unix, Control-Z on Windows)
exit()
quit()
命令行参数
脚本名称和参数都放在 sys module 的 argv 变量。
The length of the list is at least one; when no script and no arguments are given, sys.argv[0] is an empty string.
When the script name is given as ‘-‘ (meaning standard input), sys.argv[0] is set to ‘-‘.
When -c command is used, sys.argv[0] is set to ‘-c’.
When -m module is used, sys.argv[0] is set to the full name of the located module.
源代码编码
默认 Python2 源代码文件使用 ASCII 编码。
在源文件第一行使用如下格式,指定编码。
1
# -*- coding: encoding -*-
例子:使用 Windows-1252 编码
1
# -*- coding: cp-1252 -*-
或者,让位 UNIX “shebang” line
1
2
#!/usr/bin/env python# -*- coding: cp-1252 -*-
注释
# 单行注释,影响范围到行末
1
2
3
4
# this is the first commentspam=1# and this is the second comment# ... and now a third!text="# This is not a comment because it's inside quotes."
数值计算
操作符
** 2个星号代表乘方,5 ** 2 == 25
其他加减乘除和其他语言一样。
String
单引号,双引号都可以界定字符串字面值。
转义操作符
\ 为转义操作符。在字符串之前加r关闭转义效果,转义操作符变成普通字符。
1
2
3
4
5
6
>>>'doesn\'t'# use \' to escape the single quote..."doesn't">>>"doesn't"# ...or use double quotes instead"doesn't">>>print'"Isn\'t," she said.'"Isn't,"shesaid.
1
2
3
4
5
>>>print'C:\some\name'# here \n means newline!C:\someame>>>printr'C:\some\name'# note the r before the quoteC:\some\name
三引号 “"”…””” or ‘'’…’’’ 用来界定多行字符串文本。
1
2
3
4
5
6
# 换行字符会自动被当成第一个字符,使用反斜杠 \ 能避免。print"""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
+ 连接字符串; * 重复字符串。
1
2
3
>>># 3 times 'un', followed by 'ium'>>>3*'un'+'ium''unununium'
2 个相邻字符串字面量,自动连接。
注意,是字面量,不是变量,变量使用 + 来与字面量连接。
1
2
3
4
5
6
7
>>>'Py''thon''Python'>>>text=('Put several strings within parentheses '...'to have them joined together.')>>>text'Put several strings within parentheses to have them joined together.'
>>>word='Python'>>>word[0]# character in position 0'P'>>>word[5]# character in position 5'n'# 序号可以为负数,从末尾开始计数。negative indices start from -1.>>>word[-1]# last character'n'>>>word[-2]# second-last character'o'>>>word[-6]'P'
提取字符串
1
2
3
4
5
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
1
2
3
4
5
6
7
8
9
10
11
12
>>>word='Python'>>>word[0:2]# characters from position 0 (included) to 2 (excluded)'Py'>>>word[2:5]# characters from position 2 (included) to 5 (excluded)'tho'>>>word[:2]# character from the beginning to position 2 (excluded)'Py'>>>word[4:]# characters from position 4 (included) to the end'on'>>>word[-2:]# characters from the second-last (included) to the end'on'
Python strings cannot be changed — they are immutable.
>>>u'Hello World !'u'Hello World !'>>>u'Hello\u0020World !'u'Hello World !'# raw mode, quote with ‘ur’>>>ur'Hello\u0020World !'u'Hello World !'>>>ur'Hello\\u0020World !'u'Hello\\\\u0020World !'
编码转换
The built-in function unicode() provides access to all registered Unicode codecs (COders and DECoders),例如Latin-1, ASCII, UTF-8, and UTF-16。 默认是 ASCII。
When a Unicode string is printed, written to a file, or converted with str(), conversion takes place using this default encoding.
1
2
3
4
5
6
7
8
9
10
>>>u"abc"u'abc'>>>str(u"abc")'abc'>>>u"äöü"u'\xe4\xf6\xfc'>>>str(u"äöü")Traceback(mostrecentcalllast):File"<stdin>",line1,in?UnicodeEncodeError:'ascii'codeccan't encode characters in position 0-2: ordinal not in range(128)
>>>x=int(raw_input("Please enter an integer: "))Pleaseenteraninteger:42>>>ifx<0:...x=0...print'Negative changed to zero'...elifx==0:...print'Zero'...elifx==1:...print'Single'...else:...print'More'...More
for
Python’s for statement iterates over the items of any sequence
1
2
3
4
5
6
7
8
>>># Measure some strings:...words=['cat','window','defenestrate']>>>forwinwords:...printw,len(w)...cat3window6defenestrate12
If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy.
1
2
3
4
5
6
>>>forwinwords[:]:# Loop over a slice copy of the entire list....iflen(w)>6:...words.insert(0,w)...>>>words['defenestrate','cat','window','defenestrate']
1
2
3
4
5
6
7
# the position index and corresponding value can be retrieved at the same time using the enumerate() function.>>>fori,vinenumerate(['tic','tac','toe']):...printi,v...0tic1tac2toe
1
2
3
4
5
6
7
8
9
# To loop over two or more sequences at the same time, the entries can be paired with the zip() function.>>>questions=['name','quest','favorite color']>>>answers=['lancelot','the holy grail','blue']>>>forq,ainzip(questions,answers):...print'What is your {0}? It is {1}.'.format(q,a)...Whatisyourname?Itislancelot.Whatisyourquest?Itistheholygrail.Whatisyourfavoritecolor?Itisblue.
1
2
3
4
5
6
7
8
9
# To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.>>>foriinreversed(xrange(1,10,2)):...printi...97531
1
2
3
4
5
6
7
8
9
# To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.>>>basket=['apple','orange','apple','pear','orange','banana']>>>forfinsorted(set(basket)):...printf...applebananaorangepear
1
2
3
4
5
6
7
# When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the iteritems() method.>>>knights={'gallahad':'the pure','robin':'the brave'}>>>fork,vinknights.iteritems():...printk,v...gallahadthepurerobinthebrave
The break statement, like in C, breaks out of the innermost enclosing for or while loop.
else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>>forninrange(2,10):...forxinrange(2,n):...ifn%x==0:...printn,'equals',x,'*',n/x...break...else:...# loop fell through without finding a factor...printn,'is a prime number'...2isaprimenumber3isaprimenumber4equals2*25isaprimenumber6equals2*37isaprimenumber8equals2*49equals3*3
continue
1
2
3
4
5
6
7
8
9
10
11
12
13
>>>fornuminrange(2,10):...ifnum%2==0:...print"Found an even number",num...continue...print"Found a number",numFoundanevennumber2Foundanumber3Foundanevennumber4Foundanumber5Foundanevennumber6Foundanumber7Foundanevennumber8Foundanumber9
pass
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
1
2
3
>>>whileTrue:...pass# Busy-wait for keyboard interrupt (Ctrl+C)...
1
2
3
4
5
# This is commonly used for creating minimal classes:>>>classMyEmptyClass:...pass...
条件操作符
The comparison operators in and not in check whether a value occurs (does not occur) in a sequence.
The operators is and is not compare whether two objects are really the same object;
Comparisons may be combined using the Boolean operators and and or
the outcome of a comparison (or of any other Boolean expression) may be negated with not.
>>>cubes=[1,8,27,65,125]# something's wrong here>>>cubes[3]=64# replace the wrong value>>>cubes[1,8,27,64,125]
追加
1
2
3
4
>>>cubes.append(216)# add the cube of 6>>>cubes.append(7**3)# and the cube of 7>>>cubes[1,8,27,64,125,216,343]
批量修改元素
1
2
3
4
5
6
7
8
9
10
11
12
13
>>>letters=['a','b','c','d','e','f','g']>>># replace some values>>>letters[2:5]=['C','D','E']>>>letters['a','b','C','D','E','f','g']>>># now remove them>>>letters[2:5]=[]>>>letters['a','b','f','g']>>># clear the list by replacing all the elements with an empty list>>>letters[:]=[]>>>letters[]
>>>squares=[]>>>forxinrange(10):...squares.append(x**2)...>>>squares[0,1,4,9,16,25,36,49,64,81]# 等价于squares=[x**2forxinrange(10)]# List Comprehensions# 等价于squares=map(lambdax:x**2,range(10))
>>>vec=[-4,-2,0,2,4]>>># create a new list with the values doubled>>>[x*2forxinvec][-8,-4,0,4,8]>>># filter the list to exclude negative numbers>>>[xforxinvecifx>=0][0,2,4]>>># apply a function to all the elements>>>[abs(x)forxinvec][4,2,0,2,4]>>># call a method on each element>>>freshfruit=[' banana',' loganberry ','passion fruit ']>>>[weapon.strip()forweaponinfreshfruit]['banana','loganberry','passion fruit']>>># create a list of 2-tuples like (number, square)>>>[(x,x**2)forxinrange(6)][(0,0),(1,1),(2,4),(3,9),(4,16),(5,25)]>>># flatten a list using a listcomp with two 'for'>>>vec=[[1,2,3],[4,5,6],[7,8,9]]>>>[numforeleminvecfornuminelem][1,2,3,4,5,6,7,8,9]
1
2
3
4
5
# List comprehensions can contain complex expressions and nested functions:>>>frommathimportpi>>>[str(round(pi,i))foriinrange(1,6)]['3.1','3.14','3.142','3.1416','3.14159']
>>>matrix=[...[1,2,3,4],...[5,6,7,8],...[9,10,11,12],...]>>>[[row[i]forrowinmatrix]foriinrange(4)][[1,5,9],[2,6,10],[3,7,11],[4,8,12]]# 等价于>>>transposed=[]>>>foriinrange(4):...transposed.append([row[i]forrowinmatrix])...>>>transposed[[1,5,9],[2,6,10],[3,7,11],[4,8,12]]# 等价于# 使用python built-in function : zip>>>zip(*matrix)[(1,5,9),(2,6,10),(3,7,11),(4,8,12)]
The del statement
The del statement can also be used to remove slices from a list or clear the entire list
1
2
3
4
5
6
7
8
9
10
11
12
13
>>>a=[-1,1,66.25,333,333,1234.5]>>>dela[0]>>>a[1,66.25,333,333,1234.5]>>>dela[2:4]>>>a[1,66.25,1234.5]>>>dela[:]>>>a[]# del can also be used to delete entire variables:>>>dela
Set
A set is an unordered collection with no duplicate elements.
Curly braces or the set() function can be used to create sets.
to create an empty set you have to use set()
support mathematical operations like union, intersection, difference, and symmetric difference.
Basic uses include membership testing and eliminating duplicate entries.
1
2
3
4
5
6
7
8
>>>basket=['apple','orange','apple','pear','orange','banana']>>>fruit=set(basket)# create a set without duplicates>>>fruitset(['orange','pear','apple','banana'])>>>'orange'infruit# fast membership testingTrue>>>'crabgrass'infruitFalse
Dictionaries
dictionaries are indexed by keys, which can be any immutable type;
think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique
A pair of braces creates an empty dictionary: {}.
keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it).
To check whether a single key is in the dictionary, use the in keyword.
# directly from sequences of key-value pairs:>>>dict([('sape',4139),('guido',4127),('jack',4098)]){'sape':4139,'jack':4098,'guido':4127}# specify pairs using keyword arguments>>>dict(sape=4139,guido=4127,jack=4098){'sape':4139,'jack':4098,'guido':4127}
dict comprehensions
1
2
>>>{x:x**2forxin(2,4,6)}{2:4,4:16,6:36}
Functions
函数定义
The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring.
1
2
3
4
5
6
7
8
9
10
>>>deffib(n):# write Fibonacci series up to n..."""Print a Fibonacci series up to n."""...a,b=0,1...whilea<n:...printa,...a,b=b,a+b...>>># Now call the function we just defined:...fib(2000)011235813213455891442333776109871597
函数说明文档
Here is an example of a multi-line docstring:
1
2
3
4
5
6
7
8
9
10
11
12
13
>>>defmy_function():..."""Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """...pass...>>>printmy_function.__doc__Donothing,butdocumentit.No,really,itdoesn't do anything.
参数
在函数体中,默认使用参数的引用。
参数缺省值
Python 支持默认参数值,在定义函数时指定,之后不可更改。
1
2
3
4
5
6
7
8
9
10
11
defask_ok(prompt,retries=4,complaint='Yes or no, please!'):whileTrue:ok=raw_input(prompt)ifokin('y','ye','yes'):returnTrueifokin('n','no','nop','nope'):returnFalseretries=retries-1ifretries<0:raiseIOError('refusenik user')printcomplaint
This function can be called in several ways:
giving only the mandatory argument: ask_ok(‘Do you really want to quit?’)
giving one of the optional arguments: ask_ok(‘OK to overwrite the file?’, 2)
or even giving all arguments: ask_ok(‘OK to overwrite the file?’, 2, ‘Come on, only yes or no!’)
1
2
3
4
5
6
7
i=5deff(arg=i):printargi=6f()# will print 5. The default value is evaluated only once.
1
2
3
4
5
6
7
8
9
10
# This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.deff(a,L=[]):L.append(a)returnLprintf(1)printf(2)printf(3)
This will print
1
2
3
[1]
[1, 2]
[1, 2, 3]
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
1
2
3
4
5
deff(a,L=None):ifLisNone:L=[]L.append(a)returnL
使用 参数名(Keyword Arguments) 调用函数
参数表类似 hash table。
使用参数名调用函数时,基于位置的参数传入要放在前面。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defparrot(voltage,state='a stiff',action='voom',type='Norwegian Blue'):print"-- This parrot wouldn't",action,print"if you put",voltage,"volts through it."print"-- Lovely plumage, the",typeprint"-- It's",state,"!"parrot(1000)# 1 positional argumentparrot(voltage=1000)# 1 keyword argumentparrot(voltage=1000000,action='VOOOOOM')# 2 keyword argumentsparrot(action='VOOOOOM',voltage=1000000)# 2 keyword argumentsparrot('a million','bereft of life','jump')# 3 positional argumentsparrot('a thousand',state='pushing up the daisies')# 1 positional, 1 keyword
*name 收拢基于位置的参数,**name 基于名字的参数
*name must occur before **name
1
2
3
4
5
6
7
8
9
defcheeseshop(kind,*arguments,**keywords):print"-- Do you have any",kind,"?"print"-- I'm sorry, we're all out of",kindforarginarguments:printargprint"-"*40keys=sorted(keywords.keys())forkwinkeys:printkw,":",keywords[kw]
It could be called like this:
1
2
3
4
5
cheeseshop("Limburger","It's very runny, sir.","It's really very, VERY runny, sir.",shopkeeper='Michael Palin',client="John Cleese",sketch="Cheese Shop Sketch")
it would print:
1
2
3
4
5
6
7
8
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
# write the function call with the *-operator to unpack the arguments out of a list or tuple:>>>range(3,6)# normal call with separate arguments[3,4,5]>>>args=[3,6]>>>range(*args)# call with arguments unpacked from a list[3,4,5]
1
2
3
4
5
6
7
8
9
# 同样,dictionaries can deliver keyword arguments with the **-operator>>>defparrot(voltage,state='a stiff',action='voom'):...print"-- This parrot wouldn't",action,...print"if you put",voltage,"volts through it.",...print"E's",state,"!"...>>>d={"voltage":"four million","state":"bleedin' demised","action":"VOOM"}>>>parrot(**d)--Thisparrotwouldn't VOOM if you put four million volts through it. E'sbleedin' demised !
Lambda Expressions
Small anonymous functions can be created with the lambda keyword.
Lambda functions can be used wherever function objects are required.
returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on.
A module is a file containing Python definitions and statements.
The file name is the module name with the suffix .py appended.
Within a module, the module’s name (as a string) is available as the value of the global variable name.
简单例子 / import some-module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# fibo.py# Fibonacci numbers moduledeffib(n):# write Fibonacci series up to na,b=0,1whileb<n:printb,a,b=b,a+bdeffib2(n):# return Fibonacci series up to nresult=[]a,b=0,1whileb<n:result.append(b)a,b=b,a+breturnresult
1
2
3
4
5
6
7
8
9
10
11
12
>>>importfibo>>>fibo.fib(1000)1123581321345589144233377610987>>>fibo.fib2(100)[1,1,2,3,5,8,13,21,34,55,89]>>>fibo.__name__'fibo'# If you intend to use a function often you can assign it to a local name:>>>fib=fibo.fib>>>fib(500)1123581321345589144233377
# in the example, fibo is not defined>>>fromfiboimportfib,fib2>>>fib(500)1123581321345589144233377# import all names that a module defines:# imports all names except those beginning with an underscore (_).>>>fromfiboimport*>>>fib(500)1123581321345589144233377
For example, the file sound/effects/init.py could contain the following code:
1
__all__=["echo","surround","reverse"]
If __all__ is not defined, the statement from sound.effects import *does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in init.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by init.py.
DEBUG
dir()
The built-in function dir() is used to find out which names a module defines.
>>>print'We are the {} who say "{}!"'.format('knights','Ni')Wearetheknightswhosay"Ni!">>>print'{0} and {1}'.format('spam','eggs')spamandeggs>>>print'{1} and {0}'.format('spam','eggs')eggsandspam>>>print'This {food} is {adjective}.'.format(...food='spam',adjective='absolutely horrible')Thisspamisabsolutelyhorrible.
‘!s’ (apply str()) and ‘!r’ (apply repr()) can be used to convert the value before it is formatted.
1
2
3
4
5
>>>importmath>>>print'The value of PI is approximately {}.'.format(math.pi)ThevalueofPIisapproximately3.14159265359.>>>print'The value of PI is approximately {!r}.'.format(math.pi)ThevalueofPIisapproximately3.141592653589793.
An optional ‘:’ and format specifier can follow the field name.
1
2
3
>>>importmath>>>print'The value of PI is approximately {0:.3f}.'.format(math.pi)ThevalueofPIisapproximately3.142.
Passing an integer after the ‘:’ will cause that field to be a minimum number of characters wide. This is useful for making tables pretty.
simply passing the dict and using square brackets ‘[]’ to access the keys
1
2
3
4
5
6
7
8
9
10
>>>table={'Sjoerd':4127,'Jack':4098,'Dcab':8637678}>>>print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '...'Dcab: {0[Dcab]:d}'.format(table))Jack:4098;Sjoerd:4127;Dcab:8637678# This could also be done by passing the table as keyword arguments with the ‘**’ notation.>>>table={'Sjoerd':4127,'Jack':4098,'Dcab':8637678}>>>print'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)Jack:4098;Sjoerd:4127;Dcab:8637678
vars(), which returns a dictionary containing all local variables.
vars(), which returns a dictionary containing all local variables.
‘w’ for only writing (an existing file with the same name will be erased)
‘a’ opens the file for appending;
‘r+’ opens the file for both reading and writing.
‘b’ appended to the mode opens the file in binary mode, so there are also modes like ‘rb’, ‘wb’, and ‘r+b’. ‘b’ 在 Windows 上有效,为兼容Windows,如果遇到二进制文件,都加上 ‘b’。
close()
When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.
with keyword
It is good practice to use the with keyword when dealing with file objects.
This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string (“”).
1
2
3
4
>>>f.read()'This is the entire file.\n'>>>f.read()''
f.readline()
f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by ‘\n’, a string containing only a single newline.
1
2
3
4
5
6
>>>f.readline()'This is the first line of the file.\n'>>>f.readline()'Second line of the file\n'>>>f.readline()''
for-loop over the file object
For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:
f.write(string) writes the contents of string to the file, returning None.
1
2
3
4
5
6
7
>>>f.write('This is a test\n')Towritesomethingotherthanastring,itneedstobeconvertedtoastringfirst:>>>value=('the answer',42)>>>s=str(value)>>>f.write(s)
文件指针位置
f.tell() returns an integer giving the file object’s current position in the file, measured in bytes from the beginning of the file.
To change the file object’s position, use f.seek(offset, from_what).
from_what value of
缺省为 0 measures from the beginning of the file
1 uses the current file position
2 uses the end of the file as the reference point.
1
2
3
4
5
6
7
8
>>>f=open('workfile','r+')>>>f.write('0123456789abcdef')>>>f.seek(5)# Go to the 6th byte in the file>>>f.read(1)'5'>>>f.seek(-3,2)# Go to the 3rd byte before the end>>>f.read(1)'d'
json module
The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing.
Reconstructing the data from the string representation is called deserializing.
# This simple serialization technique can handle lists and dictionaries, but serializing arbitrary class instances in JSON requires a bit of extra effort. json.dump(x,f)# To decode the object againx=json.load(f)
Errors and Exceptions
There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.
>>>whileTrue:...try:...x=int(raw_input("Please enter a number: "))...break...exceptValueError:...print"Oops! That was no valid number. Try again..."...except(RuntimeError,TypeError,NameError):...pass
引用exception
1
2
3
4
5
exceptValueErrorase:# orexceptValueError,e:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>>try:...raiseException('spam','eggs')...exceptExceptionasinst:...printtype(inst)# the exception instance...printinst.args# arguments stored in .args...printinst# __str__ allows args to be printed directly...x,y=inst.args...print'x =',x...print'y =',y...<type'exceptions.Exception'>('spam','eggs')('spam','eggs')x=spamy=eggs
raise 关键字: 重新抛出exception
The raise statement allows the programmer to force a specified exception to occur.
1
2
3
4
5
6
7
8
9
10
11
12
13
importsystry:f=open('myfile.txt')s=f.readline()i=int(s.strip())exceptIOErrorase:print"I/O error({0}): {1}".format(e.errno,e.strerror)exceptValueError:print"Could not convert data to an integer."except:print"Unexpected error:",sys.exc_info()[0]raise
If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:
classError(Exception):"""Base class for exceptions in this module."""passclassInputError(Error):"""Exception raised for errors in the input.
Attributes:
expr -- input expression in which the error occurred
msg -- explanation of the error
"""def__init__(self,expr,msg):self.expr=exprself.msg=msgclassTransitionError(Error):"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
prev -- state at beginning of transition
next -- attempted new state
msg -- explanation of why the specific transition is not allowed
"""def__init__(self,prev,next,msg):self.prev=prevself.next=nextself.msg=msg
Defining Clean-up Actions: finally
In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.