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..
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With