yes
yes

Reputation: 9

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.

Upvotes: 0

Views: 84

Answers (1)

Klaus D.
Klaus D.

Reputation: 14404

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 in __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 imports 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 it's not worth the effort.

Conclusion: Run the source file (.py) and let the caching mechanism do its work in the background.

Upvotes: 1

Related Questions