0

Suppose I have the following directory structure,

root
└───test
        a.py
        b.py

The file a.py contains the following:

import b

The file b.py contains the following:

print("b is imported")

If my current directory is root, and I run python test/a.py I get the following output:

b is imported

This is confusing to me, because if I start an interpreter, I cannot import b:

$ python
Python 3.10.1 | packaged by conda-forge | (main, Dec 22 2021, 01:33:54) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'b'

How is it, then, that given the same current working directory, a knows about b when I run it as a program, but not when I try to import it as a module?

user32882
  • 5,094
  • 5
  • 43
  • 82
  • 1
    ``python test/a.py`` tells Python about the ``test`` directory. A bare ``python`` doesn't. – MisterMiyagi Jan 12 '22 at 16:57
  • Working directories aren't relevant to the search path when running a script; the directory containing the main script is. See the documentation for [`sys.path`](https://docs.python.org/3/library/sys.html#sys.path) – chepner Jan 12 '22 at 17:02
  • https://realpython.com/lessons/module-search-path/ – Ouss Jan 12 '22 at 17:04

0 Answers0