6

I noticed importing an executable Python file saves a *.py[co] file, as expected, but that file also is marked executable. Randomly, I wondered if I could execute this file directly, and it worked!

Steps to duplicate:

$ echo 'print "Worked."' > testcase.py
$ chmod u+x testcase.py
$ python -c 'import testcase'
Worked.
$ ./testcase.pyc
Worked.

How did this work? Why didn't I get an error message? Is my system, Ubuntu 9.04, doing something special, or am I forgetting something on how Linux works in general?

$ python --version
Python 2.6.2
$ hd testcase.pyc
00000000  d1 f2 0d 0a a4 4f 08 4b  63 00 00 00 00 00 00 00  |.....O.Kc.......|
00000010  00 01 00 00 00 40 00 00  00 73 09 00 00 00 64 00  |[email protected].|
00000020  00 47 48 64 01 00 53 28  02 00 00 00 73 07 00 00  |.GHd..S(....s...|
00000030  00 57 6f 72 6b 65 64 2e  4e 28 00 00 00 00 28 00  |.Worked.N(....(.|
00000040  00 00 00 28 00 00 00 00  28 00 00 00 00 73 0b 00  |...(....(....s..|
00000050  00 00 74 65 73 74 63 61  73 65 2e 70 79 74 08 00  |..testcase.pyt..|
00000060  00 00 3c 6d 6f 64 75 6c  65 3e 01 00 00 00 73 00  |..<module>....s.|
00000070  00 00 00                                          |...|
00000073

(Including hexdump to show there's no shebang line, and reading about .pyc format, there's nothing here that isn't highly specific to Python.)

3 Answers 3

9

Perhaps your system has a binfmt_misc entry for .pyc files. Look in /proc/sys/fs/binfmt_misc for the entry.

0

.pyc files are byte compiled versions of the original .py file. When a .py file is executed by python, it first checks to see if there is a .pyc file with the same name and that the original .py file hasn't been modified since the .pyc file was created. It both of these are true then it executes the .pyc file because it can save the step of byte compiling the .py file thus making the execution time faster. So the .pyc file really is executable just like you discovered.

1
  • Mostly true, but don't address the question actually asked (for which Chris found the answer).
    – Roger Pate
    Dec 1, 2009 at 7:50
-1

Just because a file is marked executable does not mean that the OS knows how to execute it. What happened here is that the .pyc file inherited some of the permissions (or assumed default filesystem permissions, for example, if you're on a FAT32 drive in Linux).

In general, you don't execute .pyc files. Python stores them so it doesn't have to recompile the code every time it is imported.

1
  • 3
    True, but not the question I'm asking. I executed the file and it worked, instead of producing an error. How did that happen?
    – Roger Pate
    Nov 21, 2009 at 20:37

You must log in to answer this question.