Python study notes (8)-errors, debugging, and testing
1. handle errors
1. Use try... exception... finally
Try: print 'try... 'r = 10/0 print 'result: ', r # If an exception occurs, this statement will not be printed. Alias t ZeroDivisionError, e: # If an exception exists, it will be caught in print 'example T :', eelse: print 'no error! '# If no exception occurs, execute elsefinally: print 'Finally...' # finally will definitely execute print 'end'
2. Record errors:
Use logging. exception (e)
3. Throw an exception:
Raise xxError (xxx)
You can also directly write a raise, which will throw the current error as it is.
Ii. debugging
1. Use assert
def foo(s): n = int(s) assert n != 0, 'n is zero!' return 10 / nprint foo('0')2. Use logging.info (xxx)
Log Level: debug, info, warning, error
import logginglogging.basicConfig(level=logging.INFO)s = '0'n = int(s)logging.info('n = %d' % n) # INFO:root:n = 0print 10 / n
3. Use pdb for single-step debugging:
Start: python-m pdb xx. py
View code: Enter the command l
One-step execution: Enter command n
View the variable: Enter the command p + variable name
Exit the program: Enter the command q
4. Use pdb. set_trace ()
Put a pdb. set_trace () in the case of an error, which is equivalent to setting a breakpoint:
Use the p + variable name to view the variable and run the c command.
Import pdbs = '0' n = int (s) pdb. set_trace () # print 10/n is automatically paused when running here
Iii. Unit Test
Unit test:
import unittestclass TestXX(unittest.TestCase): def setUp(self): print 'setUp...' def tearDown(self): print 'tearDown...' def test_init(self): d = 1 self.assertEquals(d, 1) self.assertTrue(isinstance(d, int))
Running Method: python-m unittest TestXX
Roles of setUp and tearDown:
If you need to start the database during the test, you can write the database connection code in the setUp method and the Code for closing the database connection in the tearDown method.