0

I have a file structure like this:

a.py
b.py
c.py
scripts:
  --script1.py
  --script2.py

I want the scripts to be able to import files from the parent directory. What would be the best way to do this?

Ideally, I'd avoid using PYTHONPATH hacks.

Foobar
  • 7,458
  • 16
  • 81
  • 161
  • Take a look at this answer: https://stackoverflow.com/a/4383597/16569581 – samilarinc Aug 09 '22 at 23:16
  • I'm trying to avoid modifying the python path. If this means I need to re-organize my code, then so be it – Foobar Aug 09 '22 at 23:18
  • If you aren't installing your modules to a known directory on the Python search path, you are going to have to use "PYTHONPATH hacks". – chepner Aug 10 '22 at 01:01
  • That said, simply putting your scripts in the top-level directory and the modules in a subdirectory will simplify matters, because the directory containing the script is automatically added to the Python search path. – chepner Aug 10 '22 at 01:02
  • installing something (& thus mutating my local python installation) just to run a script gives me a bad taste; but maybe if that's the only way I'll have to just suck it up @chepner – Foobar Aug 10 '22 at 02:19
  • @Foobar That's what virtual environments are for. – chepner Aug 10 '22 at 11:56

1 Answers1

0

I would use:

import sys

sys.path.insert(0, full/path/to/import/folder)

import a, b, c

My IDE does not detect the module and calls it an error, but when I run the code, it works. Hopefully, it works for you too! Also, try searching stuff up like this on google, this is one of the most popular ways.