I have the following project directory. scriptA.py
and scriptB.py
are both separate micro-services, but share largely the same codebase.
myproject
apps/
models/
db.py
ModelA.py
ModelB.py
scriptA.py
scriptB.py
scripts/
import.py
requirements.text
README.md
I can run python apps/scriptA.py
and python apps/scriptB.py
just fine. They both import models/db
and models/Model(A|b)
just fine.
However, when I run python scripts/import.py
, which also tries to use models/db
, I get the following: attempted relative import with no known parent package
In scripts/import.py
, I'm using the following relative import:
from ..apps.models.db import setup_db
def main():
print("Main")
if __name__ == "__main__":
main()
scripts
is separated from apps
, because it just contains a bunch of scripts for importing data into my database. Whereas apps
contains all the code to run my applications.
From your command, I assume you're in myproject
directory while executing python apps/scriptA.py
. In that case, in import.py use:
import sys,os
sys.path.append('apps/models)
from db import setup_db
def main():
print("Main")
if __name__ == "__main__":
main()
Then you should run it normally.
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.