1

I have the following directory structure:

main_package
 | __init__.py
 | folder_1
 |  | __init__.py
 |  | folder_2
 |  |  | __init__.py
 |  |  | script_a.py
 |
 | folder_3
 |  | __init__.py
 |  | script_c.py

All the __init__.py files are empty. Here are the contents of the other three files.

script_a.py:

from ...folder_3 import script_c


print "Hello from script_a"

script_c.py:

print "Hello from script_c"

When I try to run script_a.py as shown below, it fails. This is exactly the opposite of the answer provided here.

How can I run script_a.py and import script_c.py into it? I'm using Python 2.71

$ pwd
main_package/folder_1/folder_2

$ python ./script_a.py
Traceback (most recent call last):
  File "./script_a.py", line 1, in <module>
    from ...folder_3 import script_c
ValueError: Attempted relative import in non-package
Saqib Ali
  • 11,931
  • 41
  • 133
  • 272
  • Try running as a module with the `-m` flag, explained well [here](https://stackoverflow.com/a/22250157/1034677) – tim Dec 03 '19 at 23:07

1 Answers1

1

As explained in Importing from a relative path in Python

and suggested by @tim in the comment section, if you run script by adding -m it might work.

There is another way (a.k.a the hacker way) suggested in the same topic I sent you the link.

EDIT:

import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '../..', 'folder_3'))
import script_c

This one worked for me. Could you try please? Is it okay for you to import like that?

pedro_bb7
  • 1,601
  • 3
  • 12
  • 28