0

I have a complex repository structure with multiple sub-packages:

/foo/file1.py
/foo/file2.py
/foo/bar/file3.py
/common/shared.py

(very simplified version)

All package references are either explicitly relative or absolute from the root. Everything works fine, but I need to run all scripts as modules using their full name from the root, e.g.: python -m foo.file1. The coding guideline for the repository is and will remain to use this pattern to run scripts.

Yet, is there a way to make a few files runnable as a script in this setup?

For example, I wish I could do:

if not __package__:
    __package__ = "foo.bar"

# use relative or absolute imports as if the file was run with python -m

I already tried importlib or runpy without success. Using sys.path.append makes absolute imports valid but relative imports are still an issue.

cao
  • 997
  • 9
  • 17
  • Maybe I don't get your question but, have you tried to add a `if __name__=="__main__":` to make your desired script runnable? – Btc Sources Apr 22 '20 at 17:11
  • My goal is to create a very specific file that can be run as a script (`python file.py`) and still get imports to work properly. I know how to test that my module is the main. Also `__name__ == "__main__"` is true for both `python file.py` and `python -m file`. – cao Apr 23 '20 at 07:58
  • Then I think that the first answer to this post is what you need: https://stackoverflow.com/questions/21233229/whats-the-purpose-of-the-package-attribute-in-python – Btc Sources Apr 23 '20 at 08:24
  • I do not understand how this helps. – cao Apr 23 '20 at 08:37

0 Answers0