0

I have hundreds of startup scripts in the root of my project, and they all use tools from the "tools" folder. It has become challenging to locate the specific startup script I need, so I want to organize some of the startup scripts into subfolders. However, when I move a startup script to a subfolder, I encounter an error when trying to import tools using from ..tools.test_tool import TestTool.

The error message is:

ImportError: attempted relative import with no known parent package

Is there a way to move the startup script to a subfolder while still allowing it to access the tools (and how)? Or do all startup scripts have to remain in the root folder? I'm specifically looking for a yes or no answer to this question, rather than a general explanation of how relative paths work.

Vitaliy
  • 281
  • 1
  • 2
  • 12
  • You can do this, but it requires some extra work and is not really how things are meant to work normally. The short version: the common containing folder needs to be recognized as a package for that kind of import to work. Startup scripts should usually not be put inside the package folder. Your life will be much easier if you have the startup script do an absolute import, since importing anything from within the package will necessarily establish the package root. For details, please see the linked duplicate. – Karl Knechtel May 17 '23 at 00:59
  • The best solution at the moment I see creating a `run.py` script in the root of the project containing just one line `import test_scripts.test234` and before starting `run.py` write the name of the script that I want to run in it. – Vitaliy May 17 '23 at 01:08
  • That works, and is recommended. Other approaches involve using the `-m` flag for Python and/or setting up `__main__.py` files depending on exact requirements. Again - please see the linked duplicate. – Karl Knechtel May 17 '23 at 01:10
  • I found a solution but I can't post an answer under my question – Vitaliy Jul 25 '23 at 15:53
  • Yes; that is because I closed it as a duplicate. Others who run into the same issue and find this question, should read the main Q&A instead, as it gives comprehensive answers and describes the general form the problem. – Karl Knechtel Jul 25 '23 at 19:28
  • But this question is not a duplicate! Because there is no correct answer to my question there, and my correct answer is not the right answer to that question. – Vitaliy Jul 26 '23 at 08:32
  • Yes, there is. You asked whether it is possible, and answers there show a way to do it. – Karl Knechtel Jul 26 '23 at 08:35
  • Okay, then my solution will remain with me. You can delete this question. – Vitaliy Jul 26 '23 at 10:15

0 Answers0