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
1
  • Try running as a module with the -m flag, explained well here Commented Dec 3, 2019 at 23:07

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. The Hacker Way worked. Thanks. But oh god is it ugly......

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.