sphinx-autorun icon indicating copy to clipboard operation
sphinx-autorun copied to clipboard

ModuleNotFoundError when importing from working directory

Open kostrykin opened this issue 1 year ago • 5 comments
trafficstars

Importing a package from the working directory gives me a ModuleNotFoundError.

I have checked os.getcwd() and it is correct.

I have tried the most recent version of this extension, that is 2649928e013d4a6a80fbf66485860692ee2d3d5d.

I guess that the error is due to sys.path not containing the working directory:

[
  '/working-directory/.venv/lib/python3.11/site-packages/sphinx_autorun',
  '/opt/homebrew/Caskroom/miniforge/base/envs/my-conda-env/lib/python311.zip',
  '/opt/homebrew/Caskroom/miniforge/base/envs/my-conda-env/lib/python3.11',
  '/opt/homebrew/Caskroom/miniforge/base/envs/my-conda-env/lib/python3.11/lib-dynload',
  '/working-directory/.venv/lib/python3.11/site-packages'
]

kostrykin avatar Aug 18 '24 21:08 kostrykin

Python won't import modules from the current working directory. I believe that importing modules from the current working directory implicitly only worked on Python < 3.

WhyNotHugo avatar Aug 19 '24 09:08 WhyNotHugo

Thanks for the response!

I mean, if you run python from the command line, of course it will import modules from the working directory. But maybe I'm confusing apples and oranges here. However, when writing documentation for a module, let's say, mymod, how am I supposed to make this work then?

.. runblock:: pycon

    >>> import mymod

kostrykin avatar Aug 19 '24 10:08 kostrykin

I found the following solution. Add the following code to conf.py:

import os
os.environ['PYTHONPATH'] = os.path.abspath('../..') + ':' + os.environ.get('PYTHONPATH', '')

kostrykin avatar Aug 25 '24 08:08 kostrykin

You probably want sys.path.append: https://stackoverflow.com/a/3108301/107510

WhyNotHugo avatar Aug 25 '24 16:08 WhyNotHugo

When docs are built, the current directory typically changes. At least it does with the default Sphinx Makefile.

WhyNotHugo avatar Aug 25 '24 16:08 WhyNotHugo