ошибка comtypes в getModule Python: ошибка UnicodeDecodeError: кодек ‘utf-8’ не может декодировать байт 0x92 в позиции 621: недопустимый начальный байт

#python #encoding #comtypes

#python #кодирование #comtypes

Вопрос:

Я использую getModule пакета comtypes в Python. и я получаю сообщение об ошибке: ошибка UnicodeDecodeError: кодек ‘utf-8’ не может декодировать байт 0x92 в позиции 621: недопустимый начальный байт

 Below the details: 
---------------------------------------------------------------------------
SyntaxError                               Traceback (most recent call last)
    [... skipping hidden 1 frame]

<ipython-input-5-3a53f2c64cb1> in <module>
----> 1 GetModule("C:\Program Files (x86)\xxxxxxxxxxxx.exe")

~Anaconda3libsite-packagescomtypesclient_generate.py in GetModule(tlib)
    109     # create and import the module
--> 110     mod = _CreateWrapper(tlib, pathname)
    111     try:

~Anaconda3libsite-packagescomtypesclient_generate.py in _CreateWrapper(tlib, pathname)
    171     logger.info("# Generating comtypes.gen.%s", modname)
--> 172     generate_module(tlib, ofi, pathname)
    173 

~Anaconda3libsite-packagescomtypestoolstlbparser.py in generate_module(tlib, ofi, pathname)
    749 
--> 750     gen.generate_code(list(items.values()), filename=pathname)
    751 

~Anaconda3libsite-packagescomtypestoolscodegenerator.py in generate_code(self, items, filename)
    240             self.more = set()
--> 241             self.generate_all(items)
    242 

~Anaconda3libsite-packagescomtypestoolscodegenerator.py in generate_all(self, items)
    188         for item in items:
--> 189             self.generate(item)
    190 

~Anaconda3libsite-packagescomtypestoolscodegenerator.py in generate(self, item)
    184         self.done.add(item)
--> 185         mth(item)
    186 

~Anaconda3libsite-packagescomtypestoolscodegenerator.py in External(self, ext)
    628         print("import", modname, file=self.imports)
--> 629         comtypes.client.GetModule(ext.tlib)
    630 

~Anaconda3libsite-packagescomtypesclient_generate.py in GetModule(tlib)
    109     # create and import the module
--> 110     mod = _CreateWrapper(tlib, pathname)
    111     try:

~Anaconda3libsite-packagescomtypesclient_generate.py in _CreateWrapper(tlib, pathname)
    183         ofi.close()
--> 184         mod = _my_import(fullname)
    185     return mod

~Anaconda3libsite-packagescomtypesclient_generate.py in _my_import(fullname)
     23         comtypes.gen.__path__.append(comtypes.client.gen_dir)
---> 24     return __import__(fullname, globals(), locals(), ['DUMMY'])
     25 

SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0x92 in position 51: invalid start byte (_EA544A21_C82D_11D1_A3E4_00A0C90AEA82_9_6_0.py, line 1414)

During handling of the above exception, another exception occurred:

UnicodeDecodeError                        Traceback (most recent call last)
    [... skipping hidden 1 frame]

~Anaconda3libsite-packagesIPythoncoreinteractiveshell.py in showtraceback(self, exc_tuple, filename, tb_offset, exception_only, running_compiled_code)
   2028                 # Though this won't be called by syntax errors in the input
   2029                 # line, there may be SyntaxError cases with imported code.
-> 2030                 self.showsyntaxerror(filename, running_compiled_code)
   2031             elif etype is UsageError:
   2032                 self.show_usage_error(value)

~Anaconda3libsite-packagesIPythoncoreinteractiveshell.py in showsyntaxerror(self, filename, running_compiled_code)
   2090         # If the error occurred when executing compiled code, we should provide full stacktrace.
   2091         elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
-> 2092         stb = self.SyntaxTB.structured_traceback(etype, value, elist)
   2093         self._showtraceback(etype, value, stb)
   2094 

~Anaconda3libsite-packagesIPythoncoreultratb.py in structured_traceback(self, etype, value, elist, tb_offset, context)
   1469                 and isinstance(value.lineno, int):
   1470             linecache.checkcache(value.filename)
-> 1471             newtext = linecache.getline(value.filename, value.lineno)
   1472             if newtext:
   1473                 value.text = newtext

~Anaconda3liblinecache.py in getline(filename, lineno, module_globals)
     14 
     15 def getline(filename, lineno, module_globals=None):
---> 16     lines = getlines(filename, module_globals)
     17     if 1 <= lineno <= len(lines):
     18         return lines[lineno-1]

~Anaconda3liblinecache.py in getlines(filename, module_globals)
     45 
     46     try:
---> 47         return updatecache(filename, module_globals)
     48     except MemoryError:
     49         clearcache()

~Anaconda3liblinecache.py in updatecache(filename, module_globals)
    135     try:
    136         with tokenize.open(fullname) as fp:
--> 137             lines = fp.readlines()
    138     except OSError:
    139         return []

~Anaconda3libcodecs.py in decode(self, input, final)
    320         # decode input (taking the buffer into account)
    321         data = self.buffer   input
--> 322         (result, consumed) = self._buffer_decode(data, self.errors, final)
    323         # keep undecoded input until the next call
    324         self.buffer = data[consumed:]

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 621: invalid start byte
  

Я очень новичок в Python. Я искал некоторые другие решения по кодированию, которые предлагают добавить «encoding = xxx в функцию чтения», но я не знаю, как найти функцию «read» в пакете comtypes.
У кого-нибудь есть какие-либо предложения?
Большое спасибо!

Комментарии:

1. Не похоже, что есть простое / быстрое решение. Вы можете взломать библиотеку, чтобы отключить кэширование кода, установив comtypes.client.gen_dir = None . Таким образом, доступ к файловой системе не осуществляется (для кэширования кода), и поэтому процесс кодирования / декодирования обходится.

2. Для лучшего решения, что open('somefile.py').encoding производит по сравнению с файлом python encoded.py (т. Е. open('encoded.py').encoding ), который явно начинается с символов # -*- encoding: mbcs -*- (это должна быть самая первая строка файла, она не может появиться где-либо еще в файле).

3. Спасибо, Дюны! Но… Я не понял второй комментарий. Когда библиотека успешно переносится в python, действительно, python создает xxxnumberxxx.py с первой строкой # — кодирование: mbcs —

4. Второй комментарий — это то, что я прошу дополнительной информации. Я пытаюсь выяснить кодировку, которую ваш компьютер использует по умолчанию в разных сценариях. Я думаю, что автор библиотеки предположил, что это, вероятно, закончится как CP-1252, но ваша система использует что-то другое. MBCS технически не является кодировкой символов, точнее, это многобайтовый набор символов, но без указания, какой именно.

5. comtypes.client.gen_dir = None должно привести к тому, что библиотека загрузит модуль из фрагмента памяти, вместо этого создав файловый кэш и загрузив его. Проблема с кодировкой возникает из-за этого файлового кэша.