WhyNotHugo / sphinx-autorun

Sphinx extension to execute the code output it into a document.
https://pypi.python.org/pypi/sphinx-autorun
BSD 2-Clause "Simplified" License
15 stars 3 forks source link

ModuleNotFoundError when importing from working directory #61

Open kostrykin opened 4 weeks ago

kostrykin commented 4 weeks ago

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'
]
WhyNotHugo commented 3 weeks ago

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.

kostrykin commented 3 weeks ago

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 commented 3 weeks ago

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

import os
os.environ['PYTHONPATH'] = os.path.abspath('../..') + ':' + os.environ.get('PYTHONPATH', '')
WhyNotHugo commented 3 weeks ago

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

WhyNotHugo commented 3 weeks ago

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