pythondirectorypython-importrelative-import

Python How to run scripts from a subdirectory?


I have such structure of project:

lib/
    ...
scripts/
    ...

I have many Python scripts in the scripts/ directory. All of them contains relative imports: from lib import ...

So, how can I easy run scripts from the root of project /, without changing scripts (without write chdir in each script)?

Maybe can I use some __init__ file to change work dir? Or maybe can I use special command to run python scripts with root folder? Any other ways?


Solution

  • Never use chdir except if you have a very good reason. Add init files as detailed in the other answer and run your script from the parent directory (say root) as

    $ python -m scripts.yourscript # note no .py