Only Bytecode, No .py Files
Christian Heimes
lists at cheimes.de
Wed Jul 27 05:27:33 EDT 2011
Am 27.07.2011 03:32, schrieb harrismh777:
> Christian Heimes wrote:
>> The first four bytes of a pyc file contain the magic header. It must
>> match the magic of the current Python version. The next four bytes
>> contain the pyc_mtime. It must match the mtime of the corresponding .py
>> files as returned by fstat().st_mtime. If the magic doesn't match or the
>> mtime header doesn't match the mtime of the .py file, the pyc is ignored.
>
> ... so recompile is required to fix.
It's not required, you can fake a .py file with a trick:
>>> import os, struct, datetime
First get the magic and mtime from the pyc file
>>> with open("test.pyc", "rb") as f:
... header = f.read(8)
...
>>> magic, mtime = struct.unpack("ii", header)
>>> magic, mtime
(168686339, 1311717735)
Verify it's a good date
>>> datetime.datetime.fromtimestamp(mtime)
datetime.datetime(2011, 7, 27, 0, 2, 15)
Now create an empty test.py
>>> open("test.py", "w").close()
Set its mtime
>>> os.utime("test.py", (mtime, mtime))
Now the test.py has the same mtime as test.pyc and Python won't
recompile the .pyc file from the .py file as long as the magic header
(168686339) is correct.
Christian
More information about the Python-list
mailing list