Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to import a compiled python file?

Tags:

I can't seem to figure out how to import a compiled .pyc module into my code so I can use it within my main script. Is this even possible?

like image 598
Jonno Avatar asked Mar 28 '12 18:03

Jonno


People also ask

Can we import a .py file?

If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.

How do I open a Python compiled file?

If you cannot open your PYC file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a PYC file directly in the browser: Just drag the file onto this browser window and drop it.

What is Python compiled file?

pyc files are created by the Python interpreter when a . py file is imported. They contain the "compiled bytecode" of the imported module/program so that the "translation" from source code to bytecode (which only needs to be done once) can be skipped on subsequent imports if the .

Where do compiled Python files go?

Basically all python files will be compiled to directory __pythoncache__ . jb. jb.


2 Answers

If there is foo.pyc, import foo will automatically use foo.pyc whether foo.py exists or not

(If foo.py is newer, it will be used)

http://docs.python.org/tutorial/modules.html

like image 65
Intra Avatar answered Sep 21 '22 13:09

Intra


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.

If there is a source file in the same directory as the compiled file, Python will use the compiled file in the __pycache__ directory instead, or recompile from source if it's not there.

If you remove the source file without putting a ".pyc" in the same directory, the import will fail even if the compiled file exists in the __pycache__ directory. Also note that files under __pycache__ follow a different naming convention. If you copy them across, make sure that they are renamed so that it has the same name as the source file, except that the extension must be "pyc" rather than "py".

There is a very nice flow chart in PEP 3147 linked from the documentation.

like image 31
Nagev Avatar answered Sep 20 '22 13:09

Nagev