Python .elc and /etc/magic

Michael Hudson mwh at python.net
Wed Nov 14 06:35:00 EST 2001


pinard at iro.umontreal.ca (François Pinard) writes:

> Hi, friends.  I notice that the standard `file' program fails to recognise
> that `.pyc' files are compiled Python codes, and is not always clever even
> for `.py' files, witness the third line below:
> 
>    /usr/local/lib/python/Local/commun.py:    a python script text
>    /usr/local/lib/python/Local/commun.pyc:   data
>    /usr/local/lib/python/Local/defs.py:      ISO-8859 Java program text
>    /usr/local/lib/python/Local/defs.pyc:     data
>    /usr/local/lib/python/Local/machines.py:  a python script text
>    /usr/local/lib/python/Local/machines.pyc: data
>    /usr/local/lib/python/Local/make.py:      a python script text
>    /usr/local/lib/python/Local/make.pyc:     data

Dunno about .py files, but consider:

[mwh at starship mwh]$ cat get_magic.py
import imp, struct, sys
print sys.version[:3], hex(struct.unpack('l',imp.get_magic())[0])
[mwh at starship mwh]$ python1.5 get_magic.py
1.5 0xa0d4e99
[mwh at starship mwh]$ python2.0 get_magic.py
2.0 0xa0dc687
[mwh at starship mwh]$ python2.1 get_magic.py
2.1 0xa0deb2a
[mwh at starship mwh]$ python2.2 get_magic.py
2.2 0xa0ded2d

> Is there any standard `/etc/magic' entries that would work better for Python?
> Here is the Python relevant code in the copy from Linux SuSE 7.2.

Well, the above would do for the .pycs/.pyos (I can't remember if the
magic is different for .pyos -- I don't think so).  You should be able
to do

$ file /path/to/foo.pyc
Python bytecode for version 2.1

or whatever.  Identifying Python source sounds like an altogether
harder game.  Searching for ":\n    "?

>    # often the module starts with a multiline string
>    0	string		"""	a python script text
>    # MAGIC as specified in Python/import.c (1.5.2/1.6)
>    # 20121  ( YEAR - 1995 ) + MONTH  + DAY (little endian followed by "\r\n"
>    0	belong		0x994e0d0a	python compiled
> 
> It probably matters to know that Python 2.0 is the default on this system.

Where did they get that number from?  Doesn't seem to match anything I
can find.

> And even, if one knows the proper incantations, how do we proceed then
> for having that `/etc/magic' file more universally modified?

I have no idea.  I hope it's not a case of badgering each distro
separately...

Cheers,
M.

-- 
  Java sucks. [...] Java on TV set top boxes will suck so hard it
  might well inhale people from off  their sofa until their heads
  get wedged in the card slots.              --- Jon Rabone, ucam.chat



More information about the Python-list mailing list