#encoding:utf8
# Set the code - Support Chinese
1 Basics
install python2.7
wget https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz
tar xvf Python-2.7.9.tgz
cd Python-2.7.9
./configure --prefix=/usr/local/python27
make
make install
mv /usr/bin/python /usr/bin/python_old
ln -s /usr/local/python27/bin/python /usr/bin/python
python # View version
solve YUM Problems that cannot be used
vim /usr/bin/yum
vim /usr/bin/repoquery
First line of two files #!/usr/bin/python Replace with the old version python #!/usr/bin/python2.6 Note that it may be 2.4
pip Module installation
yum install python-pip # centos install pip
sudo apt-get install python-pip # ubuntu install pip
pip Official installation script
wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py
python get-pip.py
pip Compilation and installation
# https://pypi.python.org/pypi/setuptools
wget http://pypi.python.org/packages/source/s/setuptools/setuptools.tar.gz
tar zxvf setuptools.tar.gz
cd setuptools/
python setup.py build
python setup.py install
# https://pypi.python.org/pypi/ez_setup
tar zxvf ez_setup.tar.gz
cd ez_setup/
python setup.py build
python setup.py install
# https://pypi.python.org/pypi/pip
tar zxvf pip.tar.gz
cd pip/
python setup.py build
python setup.py install
Load environment variables
vim /etc/profile
export PATH=/usr/local/python27/bin:$PATH
. /etc/profile
pip freeze # Check package version
pip install -r file # List of installation package files
pip install Package # Installation package pip install requests
pip show --files Package # Check which files are installed when installing the package
pip show --files Package # See which packages have updates
pip install --upgrade Package # Update a package
pip uninstall Package # Uninstall package
pip list # see pip Installed package and version
pip install django==1.5 # Specify version installation
pip install kafka-python -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
python3 install
yum install python36.x86_64 python36-pip
view help
python -c "help('modules')" # see python All modules
import os
for i in dir(os):
print i # Module method
help(os.path) # Method help
python Key words in
import keyword
keyword.iskeyword(str) # Is the string python keyword
keyword.kwlist # return pytho All keywords
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
debugging
python -m trace -t aaaaaa.py
strace -p pid # Track system calls with system commands
Variable
r=r'\n' # When output, the prototype prints
u=u' chinese ' # Defined as unicode code
global x # Global variables
a = 0 or 2 or 1 # Boolean assignment ,a The value is True Neither deal with the back ,a The value is 2. None、 character string ''、 An empty tuple ()、 An empty list [], An empty dictionary {}、0、 Empty strings are false
name = raw_input("input:").strip() # Enter a string variable
num = int(raw_input("input:").strip()) # Input string str To int type
locals() # A dictionary of all local variables
locals().values() # A list of all local variable values
os.popen("date -d @{0} +'%Y-%m-%d %H:%M:%S'".format(12)).read() # Special cases refer to variables {0} Represents the first parameter
Dictionary based string formatting
params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
"%(pwd)s" % params # 'secret'
"%(pwd)s is not a good password for %(uid)s" % params # 'secret is not a good password for sa'
"%(database)s of mind, %(database)s of body" % params # 'master of mind, master of body'
Print
# character string %s Integers %d floating-point %f Print as is %r
print ' character string : %s Integers : %d floating-point : %f Print as is : %r' % ('aa',2,1.0,'r')
print 'abc', # There are commas , For print without wrapping , The next printing will be followed by the line printing
print '%-10s %s' % ('aaa','bbb') # Align left Occupy 10 Characters
print '%10s %s' % ('aaa','bbb') # Right alignment Occupy 10 Characters
list
# The number of list elements is the largest 536870912
shoplist = ['apple', 'mango', 'carrot', 'banana']
shoplist[2] = 'aa'
del shoplist[0]
shoplist.insert(4,'www')
shoplist.append('aaa')
shoplist[::-1] # Print backwards Valid for character flipped strings
shoplist[2::3] # Start from the second and print every three
shoplist[:-1] # Rule out the last
'\t'.join(li) # Convert the list to a string Use word table characters to divide
sys.path[1:1]=[5] # In position 1 Insert a value in the list before
list(set(['qwe', 'as', '123', '123'])) # Repeat the list through the set
eval("['1','a']") # Evaluate a string as an expression , Get the list
# enumerate The corresponding position of each value can be obtained
for i, n in enumerate(['a','b','c']):
print i,n
Tuples
# immutable
zoo = ('wolf', 'elephant', 'penguin')
Dictionaries
ab = { 'Swaroop' : '[email protected]',
'Larry' : '[email protected]',
}
ab['c'] = 80 # Add dictionary elements
del ab['Larry'] # Delete dictionary elements
ab.keys() # Check all key values
ab.values() # Print all values
ab.has_key('a') # Check whether the key value exists
ab.items() # Return to the entire dictionary list
Copy dictionary
a = {1: {1: 2, 3: 4}}
b = a
b[1][1] = 8888 # a and b All for {1: {1: 8888, 3: 4}}
import copy
c = copy.deepcopy(a) # Assign again b[1][1] = 9999 Copy the dictionary as a new dictionary , Mutual interference
a[2] = copy.deepcopy(a[1]) # Copy out the second key, They don't influence each other {1: {1: 2, 3: 4},2: {1: 2, 3: 4}}
iterator
# Create an iterative interface , Not the original object Support string 、 Sequence objects such as lists and dictionaries
i = iter('abcd')
print i.next()
s = {'one':1,'two':2,'three':3}
m = iter(s)
print m.next() # iteration key
Process structure
if Judge
# Boolean operators and or not Realize multiple judgments
if a == b:
print '=='
elif a < b:
print b
else:
print a
while loop
while True:
if a == b:
print "=="
break
print "!="
else:
print 'over'
count=0
while(count<9):
print count
count += 1
for loop
sorted() # Return a sequence ( list )
zip() # Return a sequence ( list )
enumerate() # Returns the loop list sequence for i,v in enumerate(['a','b']):
reversed() # Reverse iterator objects
dict.iterkeys() # Through key iterations
dict.itervalues() # Iterating through values
dict.iteritems() # Pass key - Value pair iteration
readline() # File iteration
iter(obj) # obtain obj iterator Check obj Is it a sequence
iter(a,b) # Repeated calls to a, Until the next value of the iterator equals b
for i in range(1, 5):
print i
else:
print 'over'
list = ['a','b','c','b']
for i in range(len(list)):
print list[i]
for x, Lee in enumerate(list):
print "%d %s Lee" % (x+1,Lee)
# enumerate Use function to get index value and corresponding value
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
The process structure is abbreviated
[ i * 2 for i in [8,-2,5]]
[16,-4,10]
[ i for i in range(8) if i %2 == 0 ]
[0,2,4,6]
tab completion
# vim /usr/lib/python2.7/dist-packages/tab.py
# python startup file
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
function
def printMax(a, b = 1):
if a > b:
print a
return a
else:
print b
return b
x = 5
y = 7
printMax(x, y)
def update(*args,**kwargs):
p=''
for i,t in kwargs.items():
p = p+ '%s=%s,' %(i,str(t))
sql = "update 'user' set (%s) where (%s)" %(args[0],p)
print sql
update('aaa',uu='uu',id=3)
modular
# Filename: mymodule.py
def sayhi():
print 'mymodule'
version = '0.1'
# Use the methods in the module
import mymodule
from mymodule import sayhi, version
mymodule.sayhi() # Use the function method in the module
Decorator
# Add additional functionality to existing functionality , Execute only once when initializing the script
#!/usr/bin/env python
def deco(func):
def wrapper(*args, **kwargs):
print "Wrap start"
func(*args, **kwargs)
func(*args, **kwargs)
print "Wrap end\n"
return wrapper
@deco
def foo(x):
print "In foo():"
print "I have a para: %s" % x
@deco
def foo_dict(x,z='dict_para'):
print "In foo_dict:"
print "I have two para, %s and %s" % (x, z)
if __name__ == "__main__":
# Decorator @deco Equivalent to foo = deco(foo)
foo('x')
foo_dict('x', z='dict_para')
result
Wrap start
In foo():
I have a para: x
In foo():
I have a para: x
Wrap end
Wrap start
In foo_dict:
I have two para, x and dict_para
In foo_dict:
I have two para, x and dict_para
Wrap end
Class object method
__xxx__ # System definition name
__init__ # Instantiate the method of the initialization class
__all__ = ['xs'] # __all__ For modules import Import time limit , Defined only all Properties specified in 、 Method 、 Classes can be imported , If it is not defined, all the data in the module will be imported
_xxx # _ The beginning is the private class , Only class objects and subclass objects can access these variables themselves Out-of-service from module import * Import class _status:
__xxx # __ The first one is the private variable name in the class , Only class objects can access , Even subclass objects can't access this data
class Person:
# Instantiate the initialization method
def __init__(self, name ,age):
self.name = name
self.age = age
print self.name
# Yes self This function is the method
def sayHi(self):
print 'Hello, my name is', self.name
# Object is called when it disappears
def __del__(self):
print 'over'
# Instantiate objects
p = Person('Swaroop',23)
# Using object methods
p.sayHi()
# Inherit
class Teacher(Person):
def __init__(self, name, age, salary):
Person.__init__(self, name, age)
self.salary = salary
print '(Initialized Teacher: %s)' % self.name
def tell(self):
Person.tell(self)
print 'Salary: "%d"' % self.salary
t = Teacher('Mrs. Shrividya', 40, 30000)
getattr(object,name,default)
# return object For the name of the name The property value of the property , If the property name There is , Then its attribute value is returned directly . If the property name non-existent , The trigger AttribetError Exception or when optional parameters default Return on definition default value
class A:
def __init__(self):
self.name = 'zhangjing'
def method(self):
print"method print"
Instance = A()
print getattr(Instance, 'name', 'not find') # If Instance There are attributes in the object name Then print self.name Value , Otherwise print 'not find'
print getattr(Instance, 'age', 'not find') # If Instance There are attributes in the object age Then print self.age Value , Otherwise print 'not find'
print getattr(Instance, 'method', 'default') # If there is a way method, Otherwise, print the address , Otherwise print default
print getattr(Instance, 'method', 'default')() # If there is a way method, Run the function and print None Otherwise print default
setattr(object,name,value)
# Set up object For the name of the name(type:string) The attribute value of the attribute of is value, attribute name It can be an existing attribute or a new attribute .
# Equal multiple self.name = name assignment Externally, you can directly transfer the corresponding relationship between variables and values
#class Person:
# def __init__(self, name ,age):
# self.name = name
# self.age = age
config = {'name':'name','age','age'}
class Configure(object):
def __init__(self, config):
self.register(config)
def register(self, config):
for key, value in config.items():
if key.upper() == key:
setattr(self, key, value)
Module package
# file ops/fileserver/__init__.py
import readers
import writers
# In the package of each module , There is one. __init__.py file , With this document , Can be imported from this directory module, When importing a package import ops.fileserver , It's actually imported __init__.py file , You can do it again __init__.py Import other packages into the file , Or modules . You don't have to put all the import The statement is written in a file , You can also reduce the amount of code , You don't need to import one by one module 了 .
# __init__.py There is an important variable __all__ . Sometimes it is necessary to import all ,from PackageName import * , At this time import Will register in the package __init__.py In file __all__ The submodules and packages in the list are imported into the current scope . Such as :
__all__ = ["Module1", "Module2", "subPackage1", "subPackage2"]
Execute all methods in the module class
# moniItems.py
import sys, time
import inspect
class mon:
def __init__(self):
self.data = dict()
def run(self):
return self.runAllGet()
def getDisk(self):
return 222
def getCpu(self):
return 111
def runAllGet(self):
for fun in inspect.getmembers(self, predicate=inspect.ismethod):
print fun[0], fun[1]
if fun[0][:3] == 'get':
self.data[fun[0][3:]] = fun[1]()
print self.data
return self.data
# Module import use
from moniItems import mon
m = mon()
m.runAllGet()
Document processing
# Pattern : read 'r' Write [ Empty the entire file ]'w' Additional [ Files need to exist ]'a' Reading and writing 'r+' Binary 'b' 'rb','wb','rb+'
Writing documents
i={'ddd':'ccc'}
f = file('poem.txt', 'a')
f.write("string")
f.write(str(i))
f.flush()
f.close()
Reading documents
f = file('/etc/passwd','r')
c = f.read().strip() # Read as a large string , And remove the last line break
for i in c.split('\n'): # Cut the string with newline characters to get the list loop for each line
print i
f.close()
Reading documents 1
f = file('/etc/passwd','r')
while True:
line = f.readline() # Back to the line
if len(line) == 0:
break
x = line.split(":") # Colon division defines sequence
#x = [ x for x in line.split(":") ] # Colon division defines sequence
#x = [ x.split("/") for x in line.split(":") ] # First colon split , stay / Division Print x[6][1]
print x[6],"\n",
f.close()
Reading documents 2
f = file('/etc/passwd')
c = f.readlines() # Read in all the documents , It can be read repeatedly , Large files take up a lot of memory
for line in c:
print line.rstrip(),
f.close()
Reading documents 3
for i in open('b.txt'): # Direct reading can also iterate , And it's good for reading large files , But don't read it repeatedly
print i,
Append log
log = open('/home/peterli/xuesong','a')
print >> log,'faaa'
log.close()
with Reading documents
# Close files automatically 、 Automatic acquisition and release of thread lock
with open('a.txt') as f:
for i in f:
print i
print f.read() # Print everything as a string
print f.readlines() # Print a list of all contents divided by lines
Random reading and writing of files
# There is no newline in the document , Everything is a character , The file also has no insert function
f.tell() # Current read / write location
f.read(5) # Read 5 Characters and change the pointer
f.seek(5) # Change the user state read / write pointer offset position , It can be written randomly
f.seek(p,0) # Move current file p Bytes , Absolute position
f.seek(p,1) # Move to... After relative to the current position p Bytes
f.seek(p,2) # Move to after the end of the relative file p Bytes
f.seek(0,2) # The pointer points to the tail
# The change pointer is beyond the end of the file , Will cause file holes ,ll Look, it takes up a lot , but du -sh But very small
f.read(65535) # Read 64K byte
f.write("str") # Writing will overwrite the response character after the current pointer , No insertion function
Built-in functions
dir(sys) # Show the properties of the object
help(sys) # Interactive help
int(obj) # Transform into plastic surgery
str(obj) # To string
len(obj) # Returns the length of an object or sequence
open(file,mode) # Open file #mode (r read ,w Write , a Additional )
range(0,3) # Returns a list of shapes
raw_input("str:") # Waiting for user input
type(obj) # Return object type
abs(-22) # The absolute value
random # random number
choice() # Returns an element of a given sequence at random
divmod(x,y) # Function to complete the division operation , Return quotient and remainder .
round(x[,n]) # Function returns a floating-point number x Round the value of , Such as given n value , Represents the number rounded to the decimal point
strip() # Is to remove more spaces at both ends of the string , This sentence is to remove the extra space at both ends of all strings in the sequence
del # Delete the data in the list
cmp(x,y) # Compare two objects # Returns an integer based on the result of the comparison , If x<y, Then return to -1; If x>y, Then return to 1, If x==y Then return to 0
max() # The largest character in a string
min() # The smallest character in a string
sorted() # Sort the sequence
reversed() # Reverse the sequence
enumerate() # Returns the index position and the corresponding value
sum() # The sum of the
list() # Become a list that can be used to iterate
eval('3+4') # Evaluate a string as an expression obtain 7
exec 'a=100' # Press the string python Statement execution
exec(a+'=new') # Put the variable a As a new variable
tuple() # Becoming tuples can be used to iterate # Data structure that cannot be changed once initialized , Velocity ratio list fast
zip(s,t) # Return a merged list s = ['11','22'] t = ['aa','bb'] [('11', 'aa'), ('22', 'bb')]
isinstance(object,int) # Test object type int
xrange([lower,]stop[,step]) # Function and range() similar , but xrnage() Don't create lists , It's back to a xrange object
List type built-in function
list.append(obj) # Add an object to the list obj
list.count(obj) # Return an object obj The number of times in the list
list.extend(seq) # Put the sequence seq Add to the list
list.index(obj,i=0,j=len(list)) # return list[k] == obj Of k value , also k The scope of i<=k<j; Otherwise abnormal
list.insert(index.obj) # When the index quantity is index Insert the object at the position of obj
list.pop(index=-1) # Delete and return the object at the specified location , The default is the last object
list.remove(obj) # Remove objects from the list obj
list.reverse() # Flip the list in place
list.sort(func=None,key=None,reverse=False) # Sort the members of the list in the specified way , If func and key Parameter assignment , Compare the elements in the specified way , If reverse The sign is set to True, The list is arranged in reverse order
Sequence type operators
seq[ind] # Get the subscript as ind The elements of
seq[ind1:ind2] # Get subscripts from ind1 To ind2 Element collection for
seq * expr # Sequence repeats expr Time
seq1 + seq2 # Connect seq1 and seq2
obj in seq # Judge obj Whether the element is contained in seq in
obj not in seq # Judge obj Whether the element is not included in seq in
String type built-in methods
string.expandtabs(tabsize=8) # tab Turn the symbol into a space # Default 8 A space
string.endswith(obj,beg=0,end=len(staring)) # Detects whether the string has been obj end , If it's a return True # If beg or end Specifies whether the detection range has been obj end
string.count(str,beg=0,end=len(string)) # testing str stay string The number of times it appears f.count('\n',0,len(f)) Determine the number of file lines
string.find(str,beg=0,end=len(string)) # testing str Is it included in string in
string.index(str,beg=0,end=len(string)) # testing str be not in string in , Abnormal transactions
string.isalnum() # If string Returns at least one character and all characters are letters or Numbers True
string.isalpha() # If string Returns at least one character and all characters are letters True
string.isnumeric() # If string Contains only numeric characters , Then return to True
string.isspace() # If string If it contains spaces, it returns True
string.isupper() # All strings are returned in uppercase True
string.islower() # Strings are all lowercase returns True
string.lower() # Convert all uppercase characters in a string to lowercase
string.upper() # Convert all lowercase characters in a string to uppercase
string.lstrip() # Get rid of string Space on the left
string.rstrip() # Get rid of string The space at the end of the character
string.replace(str1,str2) # hold string Medium str1 Replace with str2, If num Appoint , The substitution does not exceed num Time
string.startswith(obj,beg=0,end=len(string)) # Check whether the string is in obj start
string.zfill(width) # The return character length is width The characters of , Align the original string to the right , Fill in the front 0
string.isdigit() # Contains only numbers to return True
string.split("/") # hold string Slice into a list
":".join(string.split()) # With : As a separator , Merge all the elements into a new string
Dictionary building method
dict.clear() # Delete all the elements in the dictionary
dict copy() # Return dictionary ( A shallow copy ) A copy of
dict.fromkeys(seq,val=None) # Create and return a new dictionary , With seq The elements in do the key of the dictionary ,val Do the initial values of all key pairs in the dictionary
dict.get(key,default=None) # To the dictionary dict The key key, Return its corresponding value value, If the key does not exist in the dictionary , Then return to default value
dict.has_key(key) # If the key exists in the dictionary , Then return to True use in and not in Instead of
dict.items() # Returns a key containing the dictionary 、 A list of value pair tuples
dict.keys() # Returns a list of the keys in the dictionary
dict.iter() # Method iteritems()、iterkeys()、itervalues() The same as their corresponding non iterative methods , The difference is that they return an iterator , Not a list
dict.pop(key[,default]) # And methods get() be similar . If in the dictionary key Key exists , Delete and return dict[key]
dict.setdefault(key,default=None) # and set() be similar , But if it doesn't exist in the dictionary key key , from dict[key]=default Assign a value to it
dict.update(dict2) # Dictionary dict2 Key value pairs added to dictionary dict
dict.values() # Returns a list of all the values in the dictionary
dict([container]) # Factory functions for creating dictionaries . Provide container classes (container), Just fill in the dictionary with the entries
len(mapping) # Returns the length of the mapping ( key - The number of value pairs )
hash(obj) # return obj Hash value , Judge whether an object can be used as the key value of a dictionary
Ensemble method
s.update(t) # use t Element modification in s,s Now contains s or t Members of s |= t
s.intersection_update(t) # s The members in belong to s and t The elements of s &= t
s.difference_update(t) # s The members in belong to s But not included in t The elements in s -= t
s.symmetric_difference_update(t) # s The members in are updated to those contained in s or t in , But it's not s and t Common elements s ^= t
s.add(obj) # In collection s Add object in obj
s.remove(obj) # From the collection s Delete objects in obj; If obj It's not a collection s The elements in (obj not in s), Will lead to KeyError error
s.discard(obj) # If obj Is a collection s The elements in , From the collection s Delete objects in obj
s.pop() # Delete the collection s Any object in , And back to it
s.clear() # Delete the collection s All elements in
s.issubset(t) # If s yes t Subset , Then return to True s <= t
s.issuperset(t) # If t yes s Superset , Then return to True s >= t
s.union(t) # Merge operation ; Return to a new collection , The assembly is s and t Union s | t
s.intersection(t) # Intersection operation ; Return to a new collection , The assembly is s and t Intersection s & t
s.difference(t) # Return to a new collection , The change set is s Members of , But it's not t Members of s - t
s.symmetric_difference(t) # Return to a new collection , The assembly is s or t Members of , But it's not s and t Common members s ^ t
s.copy() # Return to a new collection , It's a collection s Shallow copy
obj in s # Members of the test ;obj yes s The elements in return True
obj not in s # Non member testing :obj No s Medium element return True
s == t # Equivalence test Whether they have the same elements
s != t # Inequivalence test
s < t # Subset testing ;s!=t And s All the elements in are t Members of
s > t # Superset test ;s!=t And t All the elements in are s Members of
serialize
#!/usr/bin/python
import cPickle
obj = {'1':['4124','1241','124'],'2':['12412','142','1241']}
pkl_file = open('account.pkl','wb')
cPickle.dump(obj,pkl_file)
pkl_file.close()
pkl_file = open('account.pkl','rb')
account_list = cPickle.load(pkl_file)
pkl_file.close()
File object method
file.close() # Close file
file.fileno() # Returns the descriptor of the file
file.flush() # Refresh the internal buffer of the file
file.isatty() # Judge file Is it a class tty equipment
file.next() # Returns the next line of the file , Or when there are no other rows StopIteration abnormal
file.read(size=-1) # Read from file size Bytes , When not given size Or given a negative value , Read all the remaining bytes , Then return... As a string
file.readline(size=-1) # Read from the file and return a line ( Include line terminators ), Or return to the maximum size Characters
file.readlines(sizhint=0) # Read all the lines of the file and return as a list
file.xreadlines() # For iteration , alternative readlines() A more efficient way to
file.seek(off, whence=0) # Move the file pointer in the file , from whence(0 Represents the beginning of the file ,1 Represents the current location ,2 End of representative document ) The offset off byte
file.tell() # Returns the current location in the file
file.truncate(size=file.tell()) # Intercept files to the maximum size byte , Default to current file location
file.write(str) # Write string to file
file.writelines(seq) # Write string sequence to file seq;seq It should be an iteratable object that returns a string
Properties of the file object
file.closed # Indicates that the file has been closed , Otherwise False
file.encoding # The encoding used for the file When unicode When a string is written to data , It will be used automatically file.encoding Convert to a byte string ; if file.encoding by None The system default encoding is used when using
file.mode # Access The access mode used when the file is opened
file.name # file name
file.newlines # Is... When the row separator is not read None, When there is only one line separator, it is a string , When a file has multiple types of line terminators , Is a list of all currently encountered line terminators
file.softspace # by 0 After outputting a data , Add a space character ,1 It means not to add
exception handling
# try Use in sys.exit(2) Will be captured , Cannot exit script , You can use os._exit(2) Exit script
class ShortInputException(Exception): # Inherit Exception Abnormal class , Define your own exceptions
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3) # An exception
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException, x: # Capture specified error messages
print 'ShortInputException: %d | %d' % (x.length, x.atleast)
except Exception as err: # Capture all other error messages
print str(err)
#except urllib2.HTTPError as err: # Catch errors in external import modules
#except: # Catch all other errors You won't see the error content
# print 'except'
finally: # In any case, it will be carried out Close files or disconnect, etc
print 'finally'
else: # Nothing unusual Can't and finally Same use
print 'No exception was raised.'
An uncatchable exception
NameError: # Trying to access an undeclared variable
ZeroDivisionError: # Divisor is zero.
SyntaxErrot: # Interpreter syntax error
IndexError: # The requested index element is out of sequence range
KeyError: # Request a dictionary keyword that does not exist
IOError: # Input / Output error
AttributeError: # Trying to access unknown object properties
ImportError # No modules
IndentationError # Syntax indentation error
KeyboardInterrupt # ctrl+C
SyntaxError # Code syntax error
ValueError # Wrong value
TypeError # The incoming object type does not meet the requirements
Built in exception
BaseException # The base class for all exceptions
SystemExit # python The interpreter requests exit
KeyboardInterrupt # User interrupt execution
Exception # Regular error base class
StopIteration # Iterators have no more values
GeneratorExit # Generator exception to notify exit
StandardError # All built-in standard exception base classes
ArithmeticError # Base class for all numerical errors
FloatingPointError # Floating point error
OverflowError # The numerical operation exceeds the maximum limit
AssertionError # Assertion statement failed
AttributeError # Object does not have this property
EOFError # No built-in input , arrive EOF Mark
EnvironmentError # Base class for operating system errors
IOError # Input / Output operation failed
OSError # Operating system error
WindowsError # windows System call failed
ImportError # The import module / Object failed
KeyboardInterrupt # User interrupt execution ( Usually ctrl+c)
LookupError # Base class for invalid data query
IndexError # There is no index in the sequence (index)
KeyError # There is no key in the map
MemoryError # Memory overflow error ( about python The interpreter is not fatal )
NameError # Not a statement / Initialize object ( There is no attribute )
UnboundLocalError # Accessing an uninitialized local variable
ReferenceError # If a reference attempts to access an object that has been garbage collected
RuntimeError # General runtime errors
NotImplementedError # A method that has not yet been implemented
SyntaxError # python Grammar mistakes
IndentationError # The indentation error
TabError # tab Mixed with Spaces
SystemError # General interpreter system error
TypeError # Invalid operation on type
ValueError # Invalid parameter passed in
UnicodeError # Unicode Related errors
UnicodeDecodeError # Unicode Error in decoding
UnicodeEncodeError # Unicode Errors in coding
UnicodeTranslateError # Unicode Error in conversion
Warning # The base class for warnings
DeprecationWarning # A warning about abandoned features
FutureWarning # A warning about future semantic changes in construction
OverflowWarning # Old warning about automatic promotion to long shaping
PendingDeprecationWarning # A warning that features will be discarded
RuntimeWarning # Warnings of suspicious runtime behavior
SyntaxWarning # A dubious grammatical warning
UserWarning # Warnings generated by user code
An exception
raise exclass # An exception , from exclass Generate an instance ( No exception parameters )
raise exclass() # An exception , But now it's not a class ; Call operators through functions (function calloperator:"()") Generate a new exclass example , There are also no exception parameters
raise exclass, args # An exception , But at the same time, the exception parameters args, It can be a parameter or a tuple
raise exclass(args) # An exception , ditto
raise exclass, args, tb # An exception , But provide a track record (traceback) object tb For use
raise exclass,instance # Trigger exception by instance ( Usually exclass Example )
raise instance # Trigger exception by instance ; The exception type is the type of the instance : Equivalent to raise instance.__class__, instance
raise string # Trigger string exception
raise string, srgs # Trigger string exception , But triggering comes with args
raise string,args,tb # Trigger string exception , But provide a track record (traceback) object tb For use
raise # Re trigger the previous exception , If there is no abnormality before , Trigger TypeError
Trace exception stack
# traceback Get exception related data through sys.exc_info() Function to get
import traceback
import sys
try:
s = raw_input()
print int(s)
except ValueError:
# sys.exc_info() The return value is a tuple , first exc_type Is an unexpected object type ,exc_value Is an abnormal value ,exc_tb It's a traceback object , The object contains the number of rows in error 、 Location, etc
exc_type, exc_value, exc_tb = sys.exc_info()
print "\n%s \n %s \n %s\n" %(exc_type, exc_value, exc_tb )
traceback.print_exc() # Print stack trace information
Capture all error messages and store them in a dictionary
import sys, traceback
try:
s = raw_input()
int(s)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback_details = {
'filename': exc_traceback.tb_frame.f_code.co_filename,
'lineno' : exc_traceback.tb_lineno,
'name' : exc_traceback.tb_frame.f_code.co_name,
'type' : exc_type.__name__,
'message' : exc_value.message,
}
del(exc_type, exc_value, exc_traceback)
print traceback_details
f = file('test1.txt', 'a')
f.write("%s %s %s %s %s\n" %(traceback_details['filename'],traceback_details['lineno'],traceback_details['name'],traceback_details['type'],traceback_details['message'], ))
f.flush()
f.close()
debugging log
# cgitb Override default sys.excepthook Global exception interceptor
def func(a, b):
return a / b
if __name__ == '__main__':
import cgitb
cgitb.enable(format='text')
func(1, 0)
Built in functions for functional programming
apply(func[,nkw][,kw]) # Call... With optional parameters func,nkw Is a non keyword parameter ,kw For keyword parameters ; The return value is the return value of the function call
filter(func,seq) # Call a Boolean function func To iterate through each seq The elements in ; Return to a func The return value is true Sequence of elements of
map(func,seq1[,seq2]) # Will function func Act on a given sequence (s) Each element of , And use a list to provide the return value ; If func by None,func As an identity function , Returns a... That contains a collection of elements in each sequence n A list of tuples
reduce(func,seq[,init]) # Apply a binary function to seq Elements of sequence , Carry one pile at a time ( Previous results and next sequence elements ), Continuously apply the existing result and the next value to the subsequent result obtained , Finally, reduce our sequence to a single return value ; If the initial value init Given , The first comparison would be init And the first sequence element instead of the first two elements of the sequence
lambda x,y:x+y # Create an anonymous function It can be used to directly create anonymous function expressions in the above methods
# filter That is, only the values whose results are true are kept to form a list through the function method
def f(x): return x % 2 != 0 and x % 3 != 0
f(3) # The result of the function is False 3 By filter abandon
f(5) # The result of the function is True 5 Be added filter The final list result
filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
# map The list is processed by the function to get a new list
def cube(x): return x*x*x
map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
# reduce The function will first receive the initial value and the first element of the sequence , Then there is the return value and the next element , And so on
def add(x,y): return x+y
reduce(add, range(1, 11)) # result 55 yes 1 To 10 And x The value of is the result returned by the last function ,y Is the value of the loop in the list
reduce(lambda x,y:x+y, range(1,11)) # Equal to the above two lambda To create anonymous functions [ lambda x,y:x+y ] , Followed by iteratable objects
Encoding conversion
a=' chinese ' # Code not defined by input terminal utf8 or gbk
u=u' chinese ' # Defined as unicode code u The value is u'\u4e2d\u6587'
u.encode('utf8') # To utf8 Format u The value is '\xe4\xb8\xad\xe6\x96\x87'
print u # Results show chinese
print u.encode('utf8') # To utf8 Format , When the display terminal code is utf8 Results show chinese If the code is inconsistent, it will be messy
print u.encode('gbk') # The current terminal is utf8 So the random code
ord('4') # Character conversion ASCII code
chr(52) # ASCII Code to character
Set read code to utf8 Avoid conversion errors
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
Traversal recursion
[os.path.join(x[0],y) for x in os.walk('/root/python/5') for y in x[2]]
for i in os.walk('/root/python/5/work/server'):
print i
The metaclass
# Implementation dynamics curd Method attributes of a class or instance
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Name: metaclass.py
# Author: ZhiPeng Wang.
# Created: 15/8/12
# Copyright: (c) TigerJoys-SA 2015
# -----------------------------------------------------------------------------
""" First check __metaclass__ attribute , If this property is set , If this property is set, the corresponding Metaclass,
Metaclass Itself is also Class When calling, first call its own __new__ Method to create a new Instance then Instance transfer
use __init__ Return a new object (MyClss), Then execute the original Class
"""
ext_attr = {
'wzp': 'wzp',
'test': 'test',
}
class CustomMeta(type):
build_in_attr = ['name', ]
def __new__(cls, class_name, bases, attributes):
# obtain `Meta` Instance
attr_meta = attributes.pop('Meta', None)
if attr_meta:
for attr in cls.build_in_attr: # Traverse built-in properties
# introspection , obtain Meta Attributes No build_in_attr Property of does not handle
print "Meta:", getattr(attr_meta, attr, False)
# Extended attributes
attributes.update(ext_attr)
return type.__new__(cls, class_name, bases, attributes)
def __init__(cls, class_name, bases, attributes):
super(CustomMeta, cls).__init__(class_name, bases, attributes)
class MyClass(object):
__metaclass__ = CustomMeta # metaclass
class Meta:
name = 'Meta attr'
if __name__ == '__main__':
# TODO A class is returned here `Instance` object
print MyClass()
# TODO A class object is returned here , Not at all `Instance`
print type("MyClass", (), {})
Recommended by Ali Test Engineer -- using selenium to obtain dynamic page data in Python
utilize python Crawling websit
Most beginners learn Python and web automation. In this way, they learn and give up
Heres the catalog title