如何在没有unicode错误的情况下执行pyc文件

时间:2017-06-27 07:50:58

标签: python unicode

我有一个" insval.py"文件,当我在IDE上导入它时 - 已经创建了一个" insval.pyc"。

然后,当我试图运行一个pyc文件时,我发现了这个错误:

1)

exec(open(r'D:\BPO Helper\firms\insval\insval.pyc').read())
File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\encodings\cp1251.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 391: character maps to <undefined>

2)

exec(open(r'D:\BPO Helper\firms\insval\insval.pyc', encoding='ansi').read())
ValueError: source code string cannot contain null bytes

3)

exec(open(r'D:\BPO Helper\firms\insval\insval.pyc', encoding='cp1251').read())
File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\encodings\cp1251.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 391: character maps to <undefined>

4)

exec(open(r'D:\BPO Helper\firms\insval\insval.pyc', encoding='utf-8').read())
File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe3 in position 12: invalid continuation byte

我怎能避免这种情况?

2 个答案:

答案 0 :(得分:0)

而不是<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp"> </Button> </LinearLayout> , 试试D:\BPO Helper\firms\insval\insval.pyc'

答案 1 :(得分:0)

*.pyc文件不是文本文件,因此您需要以二进制模式打开它们,否则Python会尝试将它们解码为ascii / utf-8并失败。

pyc_file = r"D:\BPO Helper\firms\insval\insval.pyc"
with open(pyc_file, "rb") as pyc:
    exec(pyc.read())

但是,除非你在名为*.pyc的文件中有实际的来源,否则这将无效。您不能以这种方式执行编译的代码,但是您可以导入它:

import sys
sys.path.append(r"D:\BPO Helper\firms\insval")
import insval

但我仍然不明白你为什么要这样做。只是不要编译你的Python文件(Python会在后面为你做这件事)并以正常的方式加载它们。

更新 - 如果你真的坚持走这条.pyc道路,你最终可以加载你的.pyc文件,解组它们,提取代码对象和然后让它由exec()运行。

# here be dragons, you've been warned
import marshal

pyc_file = r"D:\BPO Helper\firms\insval\insval.pyc"
with open(pyc_file, "rb") as pyc:
    pyc.seek(8)  # skip the header, for Python v3.3+ pyc's use 12 bytes instead 
    code = marshal.load(pyc)  # unmarshal the pyc into code object(s)
    exec(code)  # with some luck, this will work

这太脆弱了,不能用于任何类型的生产代码,但如果你坚持的话,那就再次......