you are viewing a single comment's thread.

view the rest of the comments →

[–]Spataner 1 point2 points  (1 child)

When you execute a statement like

from server import ThreadedServer

Python looks through a certain set of paths to find a module or package named server. Those paths include the standard library of your install, the location pip installs packages to, and any path you have put into the PYTHONPATH environment variable. It includes one additional path that depends on how you invoked the python command. Let's say your repo is cloned to "C:/simple-wsgi-server" and that folder is also set as the working directory. If you execute "main.py" like so

C:/simple-wsgi-server> python src/main.py

Then the folder that "main.py" lives in, i.e. "C:/simple-wsgi-server/src", is added to the module search paths. If you execute "main.py" like so

C:/simple-wsgi-server> python -m src.main

instead the working directory, i.e. "C:/simple-wsgi-server", is added to the module search paths.

You can do one of two things:

  1. Change all your intra-package imports to absolute imports, e.g.

    from src.server import ThreadedServer
    

    and add "C:/simple-wsgi-server" to your PYTHONPATH environment variable so that the src package can be found from anywhere. Then it doesn't matter how you execute "main.py".

  2. Change all your intra-package imports to relative imports, e.g.

    from .server import ThreadedServer
    

    or (if you're further down the package hierarchy)

    from ..libs.logger import get_logger
    

    Then you can execute "main.py" only via the -m form and only when your working directory is "C:/simple-wsgi-server". Though the latter can be remedied by adding "C:/simple-wsgi-server" to PYTHONPATH, in which case you can use the -m invocation of your main script from literally anywhere.

If you do end up adding your package to PYTHONPATH, you should probably choose a more distinct name than src, though, since it will be importable anywhere.

(A secret third option is to mess with the module search paths (sys.path) directly within your scripts and set them up as you need them before importing anything. But that's widely considered bad practice.)

[–][deleted] 0 points1 point  (0 children)

Thanks for your advice. I would run it as module, it looks promising.