Reputation: 1585
I Try this in Python 3.3
f = open(r'somewhere\my_module.pyc','rb')
contents = f.read()
f.close()
code_obj = marshal.loads(contents[8:])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: bad marshal data (unknown type code)
I get error , so i convert contents
variable type to str
def bytes2str(byte_seq):
str_seq = ''
for b in byte_seq:
str_seq += chr(b)
return str_seq
contents = bytes2str(contents)
code_obj = marshal.loads(contents[8:])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface
When i try this in Python 2.7 i get a code object. How to deal with this problem without using compile
built-in function?
Upvotes: 5
Views: 2507
Reputation: 104762
It seems the header of a .pyc
file has changed in recent versions of Python to be 12 bytes, rather than 8. If you do code_obj = marshal.loads(contents[12:])
, you'll get the code object you are seeking.
I've tried in vain to find documentation of this change to the PYC file format, but so far I've not had any luck. It seems like it started with Python 3.3 (which included quite a lot of changes to the import machinery), but I'm not sure which bit required the extra 4 bytes.
Upvotes: 6