【问题标题】:Python scripts in different directories use the same file in which import breaks不同目录中的 Python 脚本使用导入中断的相同文件
【发布时间】:2021-02-04 19:05:59
【问题描述】:

所以我有一个这样的树文件:

scriptA.py
folder/
------scriptB.py
------some_function.py
------utils.py

文件 some_function.py 从文件 utils.py 导入一些内容,并且两个脚本(scriptA.pyscriptB.py)都使用来自 some_function.py 文件的函数。问题是在some_function.py 中导入。它从utils.py 导入一些东西,当我运行scriptA.py 时,它必须是from folder.utils import smth,但是当我运行scriptB.py 时,它必须是from utils import smth。如何使该导入在这两种情况下都起作用?

编辑:
scriptA.py 运行烧瓶应用程序
scriptB.py 运行一些普通的 python 脚本

【问题讨论】:

  • 你可以尝试在你的 some_functions.py 中使用相对导入使用from .utils import smth
  • 那么我在该相对导入中得到ImportError: attempted relative import with no known parent package

标签: python file flask import directory


【解决方案1】:

我可以让它工作:

├── a.py
└── folder
    ├── b.py
    ├── somefunction.py
    └── utils.py

utils.py

dummy = 123

somefunction.py

from .utils import dummy

b.py

from .somefunction import dummy
print(dummy)

a.py

from folder.somefunction import dummy
print(dummy)

然后你可以通过以下方式在同一位置执行 a 和 b:

jamess-mbp-2:demo jlin$ python a.py 
123
jamess-mbp-2:demo jlin$ python -m folder.b
123

【讨论】:

  • 谢谢它完美的工作。我缺少的东西是以错误的方式运行b.py。您能否解释一下为什么使用标志-mfolder.b 表示法?
  • b.pyfolder 包内的一个模块,-m 是“将模块作为脚本运行”。
猜你喜欢
  • 2019-03-20
  • 1970-01-01
  • 2018-05-11
  • 2021-10-16
  • 2020-03-28
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多