简体   繁体   中英

importing files from different directories

I have the folder structure as follows:

project1/app1/app1.py
project1/app2/app2.py

I want to import app1.py to app2.py I have tried:

sys.path.insert(0, 'project1/app1')
from app1 import a1

It worked fine but i dont want to hardcode the path. Inshort I dont want to use sys to import path. I want something like this:

from app1.app1 import a1

Please give me some sort of advice. Thanks in advance.

prj/
├── project1/
│   ├── __init__.py
│   └── app1/
│       └── app1.py
│
└── project2/
    ├── __init__.py
    └── app2/
        └── app2.py

This makes project1 and project2 folder to packages

app1.py
greet = "Hello"

app2.py
from ...prj1.app1.app1 import *
print(greet)

Output
D:\code>>python -m prj.prj2.app2.app2
HI

As these are packages and need to be loaded, they should be run from prj folder level with -m flag

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