1

I'm trying to organize my python files to keep everything neat and I'm trying to figure out how best to call one file from one module by another file in another module. I've seen various path explanations, but I don't really understand their explanations. This is what my file structure looks like:

Source
 │   Main.py
 │
 ├───utils
 │       listOfAllNames.py
 │
 └───helpers
         printer.py

In Main.py I call printer.py as a subprocess and printer.py imports listOfNames.py so that it can access the names it needs to print. I do this by saying: from utils import listOfAllNames

If I call printer.main() in Main.py then it works as intended because Main.py's location has a folder called 'utils' to pull from, but when I call it as a subprocess, printer.py has no utils in its folder to work with. I've tried importing like this: from ..utils import listOfAllNames, but then I get the error: ImportError: attempted relative import with no known parent package.

I don't know how to make printer.py realize that there is indeed a parent.

I know the easy way is to have everything in the same folder, but I want things to be organized, as there will be a lot of files going into this.

6
  • What if you refer directly to the parent directory like from .. import listOfAllNames? Commented Jan 13, 2022 at 17:08
  • 1
    @RichardKYu that would not work as there is no parent package if OP is running it as a subprocess. Relative imports only work when there is a parent package. Running it as a subprocess means printer.py's __name__ is "__main__" and has no parent. Commented Jan 13, 2022 at 17:22
  • Can you include how you call it as a subprocess? Commented Jan 13, 2022 at 17:23
  • @Axe319 Yes, I call it like this: p = subprocess.Popen(["python", "helpers/printer.py"]) Commented Jan 13, 2022 at 17:28
  • 1
    @Axe319 That worked! Tysm Commented Jan 13, 2022 at 22:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.