[英]Python attempted relative import with no known parent package
I have the following project directory.我有以下项目目录。
scriptA.py
and scriptB.py
are both separate micro-services, but share largely the same codebase. scriptA.py
和scriptB.py
都是独立的微服务,但在很大程度上共享相同的代码库。
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.我可以运行
python apps/scriptA.py
和python apps/scriptB.py
就好了。 They both import models/db
and models/Model(A|b)
just fine.他们都可以导入
models/db
和models/Model(A|b)
。
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
但是,当我运行
python scripts/import.py
时,它也尝试使用models/db
,我得到以下信息: attempted relative import with no known parent package
In scripts/import.py
, I'm using the following relative import:在
scripts/import.py
中,我使用以下相对导入:
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. scripts
与apps
是分开的,因为它只包含一堆用于将数据导入我的数据库的脚本。 Whereas apps
contains all the code to run my applications.而
apps
包含运行我的应用程序的所有代码。
From your command, I assume you're in myproject
directory while executing python apps/scriptA.py
.根据您的命令,我假设您在执行
python apps/scriptA.py
时位于myproject
目录中。 In that case, in import.py use:在这种情况下,在 import.py 中使用:
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.然后你应该正常运行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.