1"""Encoding utilities""" 2 3import os 4import sys 5 6try: 7 import builtins 8except ImportError: 9 import __builtin__ as builtins 10 11__all__ = ['b', 'bchr', 'bytestype', 'envencode', 'fsdecode', 'fsencode', 12 'stdoutb', 'stderrb', 'u', 'ul', 'unicodetype'] 13 14bytestype = getattr(builtins, 'bytes', str) 15unicodetype = getattr(builtins, 'unicode', str) 16 17if getattr(os, 'fsdecode', None) is not None: 18 fsdecode = os.fsdecode 19 fsencode = os.fsencode 20elif bytestype is not str: 21 if sys.platform == 'win32': 22 def fsdecode(s): 23 """Decode a filename from the filesystem encoding""" 24 if isinstance(s, unicodetype): 25 return s 26 encoding = sys.getfilesystemencoding() 27 if encoding == 'mbcs': 28 return s.decode(encoding) 29 else: 30 return s.decode(encoding, 'surrogateescape') 31 32 def fsencode(s): 33 """Encode a filename to the filesystem encoding""" 34 if isinstance(s, bytestype): 35 return s 36 encoding = sys.getfilesystemencoding() 37 if encoding == 'mbcs': 38 return s.encode(encoding) 39 else: 40 return s.encode(encoding, 'surrogateescape') 41 else: 42 def fsdecode(s): 43 """Decode a filename from the filesystem encoding""" 44 if isinstance(s, unicodetype): 45 return s 46 return s.decode(sys.getfilesystemencoding(), 'surrogateescape') 47 48 def fsencode(s): 49 """Encode a filename to the filesystem encoding""" 50 if isinstance(s, bytestype): 51 return s 52 return s.encode(sys.getfilesystemencoding(), 'surrogateescape') 53else: 54 def fsdecode(s): 55 """Decode a filename from the filesystem encoding""" 56 return s 57 58 def fsencode(s): 59 """Encode a filename to the filesystem encoding""" 60 return s 61 62if bytestype is str: 63 def envencode(s): 64 """Encode a byte string to the os.environ encoding""" 65 return s 66else: 67 envencode = fsdecode 68 69if getattr(sys.stdout, 'buffer', None) is not None: 70 stdoutb = sys.stdout.buffer 71 stderrb = sys.stderr.buffer 72else: 73 stdoutb = sys.stdout 74 stderrb = sys.stderr 75 76if bytestype is str: 77 def b(s): 78 """Convert an ASCII string literal into a bytes object""" 79 return s 80 81 bchr = chr 82 83 def u(s): 84 """Convert an ASCII string literal into a unicode object""" 85 return s.decode('ascii') 86else: 87 def b(s): 88 """Convert an ASCII string literal into a bytes object""" 89 return s.encode('ascii') 90 91 def bchr(i): 92 """Return a bytes character for a given integer value""" 93 return bytestype([i]) 94 95 def u(s): 96 """Convert an ASCII string literal into a unicode object""" 97 return s 98 99try: 100 eval(r'u""') 101except SyntaxError: 102 ul = eval 103else: 104 def ul(e): 105 """Evaluate e as a unicode string literal""" 106 return eval('u' + e) 107