简体   繁体   中英

How to import python script from a different directory using relative paths?

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

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 (aka 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM