Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot run a specific .pyc file

Tags:

python

pyc

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..

like image 348
Lazykiddy Avatar asked Oct 20 '12 11:10

Lazykiddy


People also ask

Can we run .PYC file?

pyc exists (which is the byte-code compiled version of myprog.py ), and if it is as recent or more recent than myprog.py . If so, the interpreter runs it. If it does not exist, or myprog.py is more recent than it (meaning you have changed the source file), the interpreter first compiles myprog.py to myprog.

What is .PYC file in Python?

pyc file is created by the Python interpreter when a *. py file is imported into any other python file. The *. pyc file contains the “compiled bytecode” of the imported module/program so that the “translation” from source code to bytecode can be skipped on subsequent imports of the *. py file.

How do I import a .PYC file?

In a nutshell, to import a Python compiled file (e.g. module. pyc) only, simply place it in the same directory where the source (e.g module.py) would be, and ensure that there is no corresponding source file (module.py in our example) there. Then the usual import module will work seamlessly.


2 Answers

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.

like image 86
Dietrich Epp Avatar answered Oct 10 '22 06:10

Dietrich Epp


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
like image 6
Marwan Alsabbagh Avatar answered Oct 10 '22 05:10

Marwan Alsabbagh