0

How can I use a common include file in multiple subfolders?

Example:

Main_Folder
 |
 | vars.py
 |
 | folder_1
 |  | script.py
 |
 | folder_2
 |  | script.py
 |
 | folder_3
 |  | script.py

So for sample I have a variable "foo" in vars.py that I want to reference in folder's 1, 2, and 3.

Stan
  • 11
  • 1
  • From the scripts in the subfolder try importing vars.py https://stackoverflow.com/questions/714063/importing-modules-from-parent-folder – rubensoleao Jan 21 '21 at 12:46

1 Answers1

0

I tested this, and it's very simple. Just put this at the beginning of your scripts:

import vars

Then you can do:

vars.foo
Crabby Fish
  • 140
  • 2
  • 10
  • That's not working because vars is one level higher: ``` (.venv) le % python3 test.py Traceback (most recent call last): File "test.py", line 1, in import vars ModuleNotFoundError: No module named 'vars' (.venv) le % ls ../ |grep vars vars.py ``` – Stan Jan 21 '21 at 11:56
  • @CrabbyFish This dependent on where the script is run from, the entry point, or possibly another reason. Because it works on one PC doesn't necessarily mean it'll run on another if it's not being run the same way. You'll notice OP's traceback shows he's running `test.py` but his question never shows a `test.py`. – Axe319 Jan 21 '21 at 14:31
  • test.py is in folder1/ – Stan Jan 21 '21 at 15:27
  • In that case, `import sys; sys.path.append('..'); from vars import foo; print(foo)` in your `test.py` should work if running from within `folder_1`. – Axe319 Jan 21 '21 at 15:52