Is it possible to import a compiled python file?

ぃ、小莉子 提交于 2019-12-09 00:32:21

问题


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.



来源:https://stackoverflow.com/questions/9913193/is-it-possible-to-import-a-compiled-python-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!