How to run a .pyc (compiled python) file?

When I compile a python file, I get a *.pyc file. When I try to run that, I get a message saying there is no program for running them. When I search for a program online via that option, it says there are none. Can anyone help me run there files?


Solution 1:

Since your python file is byte compiled you need to run it through the python interpreter

python yourfile.pyc

The reason you can run your .py files directly is because you have the line

#!/usr/bin/python

or

#!/usr/bin/env python

or something similar on the first line in the .py files. This tells your shell to execute the file with the Python interpreter.

Solution 2:

To decompile compiled .pyc python3 files, I used uncompyle6 in my current Ubuntu OS as follows:

  1. Installation of uncompyle6:

    pip3 install uncompyle6
    
  2. To create a .py file from .pyc file Run:

    uncompyle6 -o . your_filename.pyc
    
  3. Automatically a new .py file will be created with the same existing .pyc file name.

Solution 3:

Python compiles the .py files and saves it as .pyc files so it can reference them in subsequent invocations. The .pyc contain the compiled bytecode of Python source files, which is what the Python interpreter compiles the source to. This code is then executed by Python's virtual machine. There's no harm in deleting them (.pyc), but they will save compilation time if you're doing lots of processing.

Python is an interpreted language, as opposed to a compiled one, though the distinction can be blurry because of the presence of the bytecode compiler. Compiling usually means converting to machine code which is what runs the fastest. But interpreters take human-readable text and execute it. They may do this with an intermediate stage.

For example, When you run myprog.py source file, the python interpreter first looks to see if any myprog.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.

There is one exception to the above example. If you put #! /usr/bin/env python on the first line of myprog.py, make it executable, and then run myprog.py by itself.