7

After compiling a in unix-working python file using

import py_compile
py_compile.compile('server.py')

I get the .pyc file in the same directory, but when I try to run this file using './server.pyc' in putty all I get is scrambled code as an output and nothing really happens.

So the question is, how to compile a .py file properly to a .pyc file and how to run this .pyc file?

ps: I did test compiling & running a basic script, which worked..

Lazykiddy
  • 1,525
  • 1
  • 11
  • 18
  • 2
    Is there a good reason not to execute the source `.py` file directly? – Markus Unterwaditzer Oct 20 '12 at 11:31
  • Maybe not some reasons good enough, but turning py to pyc is a kind of obfuscation that is a very weak one but is better than doing nothing. Also pyc files save the time spent on compiling py to byte code, so the program starts up a little faster at the first time. – ebk Mar 26 '21 at 02:07

2 Answers2

14

Compiling a python file does not produce an executable, unlike C. You have to interpret the compiled Python code with the Python interpreter.

$ python
>>> import py_compile
>>> py_compile.compile('server.py')
>>> ^D
$ python ./server.pyc

The only change compiled Python code has is that it takes slightly less time to load. The Python interpreter already compiles code when it is loaded, and that doesn't take very long at all.

DSM
  • 342,061
  • 65
  • 592
  • 494
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • 6
    @MarwanAlsabbagh: Then fix it. You haven't told me where it is, and I don't like playing games. – Dietrich Epp Oct 20 '12 at 11:26
  • @DietrichEpp Thanks! I know this is an old answer but still, it deserves *way* more up-votes, once again thanks for the help, really made my day. –  Dec 22 '16 at 00:01
6

Run the first command to generate the server.pyc file. Then the second command can run the server.pyc module. The -c option and -m option are described in the python docs.

python -c "import server"
python -m server
Marwan Alsabbagh
  • 25,364
  • 9
  • 55
  • 65
  • The `-m` way to start a Python program is great because it works with both pyc and py files. Even if you deploy a program in a pyc-only form, the command still works. – ebk Mar 26 '21 at 01:52