Python venv ModuleNotFoundError

五迷三道 提交于 2019-12-04 22:00:06

It's a somewhat murky situation IMHO. My solution to this is: create a setup.py for your project (beneficial anyways), and with activated venv do a "python setup.py develop".

That will add your project to a PTH-file, and thus you can import.

Example for a setup.py, taken from the interwebs:

# from http://python-packaging.readthedocs.io/en/latest/minimal.html

from setuptools import setup

setup(name='funniest',
      version='0.1',
      description='The funniest joke in the world',
      url='http://github.com/storborg/funniest',
      author='Flying Circus',
      author_email='flyingcircus@example.com',
      license='MIT',
      packages=['funniest'],
      zip_safe=False)

This line

​$ source project/packageB/fileB.py

fails because

  1. the import path is messed up, it includes the project folder but it should not
  2. project is possibly not in your PYTHONPATH

To fix it

Step 1) fix the import statement in fileB.py, replace your import with

​import packageA.fileA

Step 2) Confirm for yourself whether you added project to PYTHONPATH by checking your bash environment

​$ echo $PYTHONPATH     # does it contain `path/to/project`?

If not temporarily fix it

​$ export PYTHONPATH=path/to/project:$PYTHONPATH   # forget `/path/to/Project` you only need `path/to/Project/project`

(Note changes to $PATH are irrelevant to Python package/module searches, so that was a wasted attempt).

Then when you run your script, it will not fail:

$ source project/packageB/fileB.py      # success?!

By the way it is better to call your python scripts with python:

$ python project/packageB/fileB.py

Finally, permanently update your virtual environment by editing the activate script in your virtual environment's bin directory. Add the PYTHONPATH export above somewhere near the top.

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