Django compiling to pyc and running server
Ok so i run
python -m compileall .
However the generated files are in pycache
manage.cpython-311.pyc and urls.cpython-311
my issue is when i run
python manage.cpython-311.pyc runserver
I keep getting the error
File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'settings'
I am not the brightest django developer. However, i would appreciate if someone shares with me how to fix this issue.
When you run Python code (and it is able to and not instructed otherwise) the interpreter will compile the imports to .pyc
files and store them in the __pycache__
folder.
On the next run the interpreter will consider these files and if they fit the source file, use them instead of repeating the compilation phase.
The files __pycache__
are not meant to be run directly, though you can do that. In your case running the file from __pycache__
moves the import base there and all the import will fail without extra adjustments.
The compileall
call will manually do this compilation step. It saves a little time on first execution. This is helpful in certain situations, like deploying your code in a large number of containers, which are expected to have a short lifetime. In most deployments its not worth the effort.
Conclusion: Run the source file (.py
) and let the caching mechanism do its work in the background.