Is it possible to import a compiled python file?

2019-02-12 22:00发布

问题:

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?

回答1:

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



回答2:

Use the import without the extension. Python will than look if the file has changed, if not it will use the previously created pyc file.

But note that if you really want more performance, I recommend you to use PyPy which is a lot faster than the standard CPython implementation. (But note that it is still Python 2)



回答3:

import module

If there's a .py source file, the core will automatically use the .pyc if it's up to date.

If there's no source, python will automatically import .pyc.

“Compiled” Python files.



回答4:

In import use the pyc file name,python will automatically load it.



回答5:

Yes, but caveat that with make sure to start python with the "-O" option! In my personal experience, if all you have is that .pyc or .pyo file, running "python.exe" without the flag and trying to import will fail, however running python.exe -O and then trying to import as normal should work.