How to get more diagnostic output on a “no module named xyz” error?

前端 未结 2 897
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 02:15

I have, in a local directory, a django project that works fine when I run it from a local django server, as in

python manage.py runserver.py 8000


        
相关标签:
2条回答
  • 2020-12-04 02:42

    This is how I would approach the problem

    1. Start interactive Python prompt

       python -vvv   # -vvv notes to print out import trace information
      
    2. Type

       import xyz
      

    If this works it means the module is valid Python installation. If it doesn't work with Django then it is a probably an issue with circular imports and problem with Django initialization code itself. Django does a lot of behind the scenes magic when it reads settings.py file, scans all Django applications and so on, so circular import is often the case why Python cannot load the module. Also this could be a case that Django swallows the original ImportError exception and does not print the nested exception what actually when wrong when initializating Django. In this case, manually typing import xyz should show you the real error.

    1. If the module loading fails then the next thing is to type

      import sys
      for p in sys.path: print(p)  # print p for Python 2.x
      

    This will show all directories where Python pulls in modules. Your module isn't probably in any of these directories so you need to make sure

    A) You append your own modules to Python sys.path list or use PYTHONPATH environment variable correctly to load your own packages. Settings up path may depend on Django version, Python version and how Django is run. For example the current working directory where you run manage.py command may or may not be included. If the module is in the current folder you can try this:

       PYTHONPATH=. python manage.py runserver
    

    B) You install your third party packages properly. The proper way to install third party Python packages is using pip tool with virtualenv isolated Python environment for your development project. If you install Python packages to system-wide Python installation (/usr/lib/python on UNIX), especially using sudo pip, the result is not guaranteed to work.

    0 讨论(0)
  • 2020-12-04 02:46

    You probably need to install the dependencies. A common thing is to store dependencies inside requirements.txt and run "pip install -r requirements.txt" when you clone a project. To push dependencies into requirements.txt you use "pip freeze > requirements.txt". So, if you project uses PIL or six or whatever it will be added to that file and then you can pip install them with a single command. I hope I haven't missed your point.

    0 讨论(0)
提交回复
热议问题