Python Run error Unicodedecodeerror

Source: Internet
Author: User
Python2.7 has a bug on Windows that runs an error:

Unicodedecodeerror: ' ASCII ' codec can ' t decode byte 0xc4 in position 33:ordinal not in range (128)

The solution is as follows:

Edit the python27\lib\mimetypes.py file, select All, replace with the correct script after the patch below, or modify it directly from this patch:

"" Guess the MIME type of a file. This module defines the useful functions:guess_type (URL, strict=1)-guess the MIME type and encoding of a URL. Guess_extension (Type, strict=1)--guess the extension for a given MIME type.  It also contains the following, for tuning the Behavior:Data:knownfiles – List of files to parseinited – flag set when Init () have been calledsuffix_map--dictionary mapping suffixes to Suffixesencodings_map--Dictionary mapping suffixes T o Encodingstypes_map--Dictionary mapping suffixes to types functions:init ([files])--Parse a list of files, default kn Ownfiles (on Windows, the default values is taken from the registry) read_mime_types (file)--parse one file, return a dic Tionary or None "" "from Itertools Import count import osimport sysimport posixpathimport urllibtry:import _winregexcept Im Porterror: _winreg = None __all__ = ["Guess_type", "Guess_extension", "Guess_all_extensions", "Add_type", "Read_mime_" Types "," init "] knownfiles = ["/etc/mime.types ","/etc/httpd/mime.types", # Mac OS X "/etc/httpd/conf/mime.types", # Apache "/etc/apache/mime.types", # apache 1 "/etc/apache2/mime.types", # Apache 2 "/usr/local/etc/httpd/conf/mime.types", "/usr/local/lib/netscape/mime.types", "/usr/local/etc/httpd/conf/mime.types", # Apache 1.2 "/usr/local/etc/mime.types", # Apache 1.3] inited = false_db = N  One class Mimetypes: "" "Mime-types datastore. This datastore can handle information from Mime.types-style files and supports basic determination of MIME type from a fil Ename or URL, and can guess a reasonable extension given a MIME type. "" "Def __init__ (Self, filenames= (), strict=true): If not inited:init () Self.encodings_map = Encodings_map.copy () s Elf.suffix_map = Suffix_map.copy () Self.types_map = ({}, {}) # Dict for (non-strict, strict) Self.types_map_inv = ({}, { }) for (ext, type) in Types_map.items (): Self.add_type (Type, ext, True) for (ext, type) in Common_types.items (): Sel F.add_type (Type, ext, False) For name in Filenames:self.read (name, strict) def add_type (self, type, ext, strict=true): "" "Add a mapping between a   Type and an extension. When the extension is already known, the new type would replace the old one.   When the type is already known the extension would be a added to the list of known extensions.  If Strict is true, information'll be added to list of standard types, else to the list of non-standard types. "" "self.types_map[strict][ext] = Type exts = Self.types_map_inv[strict].setdefault (type, []) if ext not in Exts:ext   S.append (EXT) def guess_type (self, URL, strict=true): "" "Guess the type of a file based in its URL. Return value is a tuple (type, encoding) where type was None if the type can ' t be guessed (no or unknown suffix) or a stri Ng of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The Mappings is table driven. Encodingsuffixes is case sensitive;   Type suffixes is first tried case sensitive, then case insensitive. The suffixes tgz,. Taz and. TZ (case sensitive!) is all mapped to '. tar.gz '.   (This is table-driven too, using the dictionary suffix_map.)  Optional ' strict ' argument when False adds a bunch of commonly found, but non-standard types.  "" "scheme, url = urllib.splittype (URL) if scheme = = ' data ': # Syntax of data URLs: # Dataurl: =" DATA: "[mediatype ] ["; base64"] "," data # mediatype: = [Type "/" subtype] * (";" parameter) # data: = *urlchar # parameter: =     Attribute "=" Value # Type/subtype defaults to "text/plain" comma = Url.find (', ') if comma < 0: # Bad Data URL Return None, none semi = Url.find ('; ', 0, comma) if semi >= 0:type = Url[:semi] Else:type = Url[:comm A] if ' = ' in the type or '/' not in Type:type = ' text/plain ' return type, None # never compressed, so encoding is No NE Base, ext = Posixpath.splitext (URL) while EXT in Self.suffix_map:base, ext = posixpath.splitext (base + self.suffix_map[ext]) if ext in Self.encodings_map:enco Ding = Self.encodings_map[ext] base, ext = Posixpath.splitext (base) else:encoding = None Types_map = Self.types_map [True] If ext in Types_map:return Types_map[ext], encoding elif ext.lower () in Types_map:return Types_map[ext.lowe R ()], encoding elif strict:return None, encoding types_map = Self.types_map[false] If ext in Types_map:return typ Es_map[ext], encoding elif ext.lower () in Types_map:return Types_map[ext.lower ()], encoding Else:return None, Enco   Ding def guess_all_extensions (self, type, strict=true): "" "Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('. ').  The extension is not a guaranteed to having been associated with any particular data stream, but would was mapped to the MIME   Type ' type ' by Guess_type (). Optional ' Strict ' argument when false adds a bunch of commonly found, but non-standard types. "" "type = type.lower () extensions = Self.types_map_inv[true].get (type, []) if not strict:for ext in SELF.TYPES_MAP_ Inv[false].get (type, []): If ext not in Extensions:extensions.append (EXT) return extensions def guess_extension (   Self, type, strict=true): "" "Guess the extension-a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('. ').  The extension is not a guaranteed to having been associated with any particular data stream, but would was mapped to the MIME Type ' type ' by Guess_type ().   If no extension can be guessed for ' type ', None is returned.  Optional ' strict ' argument when false adds a bunch of commonly found, but non-standard types. "" "Extensions = self.guess_all_extensions (type, strict) if not Extensions:return None return extensions[0] def Rea D (self, filename, strict=true): "" "Read a single mime.tYpes-format file, specified by pathname.  If Strict is true, information'll be added to list of standard types, else to the list of non-standard types. "" "with open (filename) as FP:SELF.READFP (FP, strict) def READFP (self, FP, strict=true):" "" Read a single Mime.typ   Es-format file.  If Strict is true, information'll be added to list of standard types, else to the list of non-standard types. "" "While 1:line = Fp.readline () if not line:break words = Line.split () for I in range (len (words)): if Wo Rds[i][0] = = ' # ': Del words[i:] break if not words:continue type, suffixes = words[0], words[1:] for Suf F in Suffixes:self.add_type (Type, '. ' + Suff, strict) def read_windows_registry (self, Strict=true): "" "Load the MI   ME types database from Windows registry.  If Strict is true, information'll be added to list of standard types, else to the list of non-standard types. "" "# Windows only if not _winreg:return def enum_types(mimedb): For I in Count (): Try:yield _winreg. EnumKey (Mimedb, i) except environmenterror:break default_encoding = Sys.getdefaultencoding () with _winreg. Openkey (_winreg. HKEY_CLASSES_ROOT, ') as Hkcr:for subkeyname in Enum_types (HKCR): Try:with _winreg. Openkey (HKCR, SubkeyName) as subkey: # Only check file extensions if not Subkeyname.startswith ("."): Conti Nue # raises EnvironmentError if no ' Content Type ' value mimetype, datatype = _winreg. QueryValueEx (subkey, ' Content Type ') if datatype! = _winreg. Reg_sz:continue Try:mimetype = Mimetype.encode (default_encoding) subkeyname = Subkeyname.encode (d  efault_encoding) except Unicodeencodeerror:continue self.add_type (MimeType, subkeyname, strict) except  Environmenterror:continue def guess_type (URL, strict=true): "" "Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the TyPE can ' t is guessed (no or unknown suffix) or a string of the form Type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The Mappings is table driven. Encoding suffixes is case sensitive;  Type suffixes is first tried case sensitive, then case insensitive. The suffixes tgz,. Taz and. TZ (case sensitive!) is all mapped to ". tar.gz".  (This is table-driven too, using the dictionary suffix_map). Optional ' strict ' argument when false adds a bunch of commonly found, but non-standard types. "" "If _db is None:init () return _db.guess_type (URL, strict) def guess_all_extensions (Type, strict=true):" "" Guess the  Extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('. '). The extension is not a guaranteed to having been associated with any particular data stream, but would being mapped to the MIME t Ype ' Type ' by Guess_type ().  If no extension can be guessed for ' type ', None is returned. Optional ' strict ' argument when false adds a bunch of commonly found, but non-standard types.  "" "If _db is None:init () return _db.guess_all_extensions (type, strict) def guess_extension (Type, strict=true):" "" Guess  The extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('. '). The extension is not a guaranteed to having been associated with any particular data stream, but would being mapped to the MIME t Ype ' type ' by Guess_type ().  If no extension can be guessed for ' type ', None is returned. Optional ' strict ' argument when false adds a bunch of commonly found, but non-standard types. "" "If _db is None:init () return _db.guess_extension (type, strict) def add_type (type, ext, strict=true):" "" Add a Mappin  g between a type and an extension. When the extension is already known, the new type would replace the old one. When the type is ALReady known the extension is added to the list of known extensions. If Strict is true, information'll be added to list of standard types, else to the list of non-standard types. "" "If _db is None:init () return _db.add_type (type, ext, strict) def init (files=none): Global Suffix_map, Types_map, en Codings_map, Common_types global inited, _db inited = True # so the mimetypes.__init__ () doesn ' t call us again db = Mimet Ypes () If files are none:if _winreg:db.read_windows_registry () files = knownfiles for file in Files:if OS.PATH.ISFI Le (file): Db.read (file) Encodings_map = Db.encodings_map Suffix_map = Db.suffix_map Types_map = db.types_map[true] Commo N_types = Db.types_map[false] # make the DB a global variable now then it is fully initialized _db = db def Read_mime_typ  Es (file): try:f = open (file) except Ioerror:return None db = Mimetypes () DB.READFP (f, True) return db.types_map[true] Def _default_mime_types (): Global Suffix_map Global ENCODINGS_MAP Global Types_maP Global Common_types Suffix_map = {'. tgz ': '. tar.gz ', '. Taz ': '. tar.gz ', '. Tz ': '. tar.gz ', '. tbz2 ': '. tar.bz2 ', '. Txz ': '. Tar.xz ',} encodings_map = {'. Gz ': ' gzip ', '. Z ': ' Compress ', '. bz2 ': ' bzip2 ', '. XZ ': ' XZ ',} # before adding new types, make sure they is either registered with I ANA, # at http://www.php.cn/# or extensions, i.e. using the-X-prefix # If You add to these, please keep them sorted! Types_map = {'. A ': ' Application/octet-stream ', '. Ai ': ' Application/postscript ', '. AIF ': ' Audio/x-aiff ', '. aifc '   : ' Audio/x-aiff ', '. Aiff ': ' Audio/x-aiff ', '. Au ': ' audio/basic ', '. avi ': ' Video/x-msvideo ', '. bat ': ' Text/plain ', '. Bcpio ': ' Application/x-bcpio ', '. Bin ': ' Application/octet-stream ', '. bmp ': ' Image/x-ms-bmp ', '. C ': ' Text/plain ', # Duplicates
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.