Advertisement
rfmonk

codecs_encode_error.py

Jan 29th, 2014
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. #1/usr/bin/env python
  2.  
  3. # this is from The Python
  4. # Standard Library by example
  5. # ISBN13: 9780321767349
  6.  
  7. import codecs
  8. import sys
  9.  
  10. error_handling = sys.argv[1]
  11.  
  12. text = u'pi: \u03c0'
  13.  
  14. try:
  15.     # Save the data, encoded as ASCII, using the error
  16.     # handling mode specified on the command line.
  17.     with codecs.open('encode_error.txt', 'w',
  18.                      encoding='ascii',
  19.                      errors=error_handling) as f:
  20.         f.write(text)
  21.  
  22. except UnicodeEncodeError, err:
  23.     print 'ERROR:', err
  24.  
  25. else:
  26.     # If there was no error writing to the file.
  27.     # show what it contains.
  28.     with open('encode_error.txt', 'rb') as f:
  29.         print 'File contents:', repr(f.read())
  30.  
  31. """
  32. usage:
  33.  
  34. $ python codecs_encode_error.py strict
  35. ERROR: 'ascii' codec can't encode character u'\u03c0'
  36. in position 4: ordinal not in range(128)
  37.  
  38. $ python codecs_encode_error.py replace
  39. File contents: 'pi: ?'
  40.  
  41. $ python codecs_encode_error.py ignore
  42. File contents: 'pi: '
  43.  
  44. $ python codecs_encode_error.py xmlcharrefreplace
  45. File contents: 'pi: π'
  46. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement