python - 多个 main 的正确 python 导入

标签 python import module

我有以下文件结构

├── test.py
└── sub
    ├── foo.py
    └── bar.py

使用 test.py:
# test.py
from sub import foo
foo.test()

和 foo.py:
# foo.py
from . import bar

def test():
  bar.test()

和 bar.py:
# bar.py
def test():
  print('This is a test')

这在从命令行调用 test.py 时工作正常。
home/$ python test.py
This is a test

现在我还希望能够直接从命令行调用 foo.py。所以我将 foo.py 更改为:
# foo.py
from . import bar

def test():
  bar.test()

if __name__ == '__main__':
  test()

但是当我调用它时它不起作用
/home$ cd sub
/home/sub$ python bar.py
Traceback (most recent call last):
  File "foo.py", line 1, in <module>
    from . import bar
ImportError: cannot import name 'bar' from '__main__' (foo.py)

这是有道理的,因为 python 文档指出

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.



所以我可以将 foo.py 中的导入语句更改为
# foo.py
import bar

但随后调用 test.py 不再起作用。
/home$ python test.py
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    from sub import foo
  File "/home/chr/code/import/sub/foo.py", line 1, in <module>
    import bar
ModuleNotFoundError: No module named 'bar'

有没有办法解决这个问题,或者根本不可能从两个不同的主电源使用 bar.py ?

编辑:一种解决方案可能是
if __name__ == '__main__':
    import bar
else:
    from . import bar

但这看起来很丑

最佳答案

您在问题中提供的解决方案绝对是其中之一。

恐怕我必须提供的其他解决方案也不是很好。但由于这是另一种解决方案,我正在写一个答案。

进行这些少量更改,它应该可以工作。

# bar.py
import bar  # use an absolute import

def test():
  bar.test()

if __name__ == '__main__':
  test()

将这两行添加到 test.py .添加到 sys.path 的路径将使该位置(模块)可用于导入。之后您可以简单地导入模块。
import sys
sys.path.append('./sub')

import foo

foo.test()

这是我的结构,和你的一样。
.
├── sub
│   ├── bar.py
│   └── foo.py
└── test.py

运行这两个文件都有效。
$ python3 test.py 
This is a test
$ python3 sub/foo.py 
This is a test

关于python - 多个 main 的正确 python 导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62375514/

相关文章:

python - 如何在每次请求 Flask 时重新加载配置文件?

以 Python 方式将 header 添加到 csv 文件

python - 如何修复 anaconda 下损坏的 pip

python - 更新多线程 PyQT 中的 GUI 元素

sql - 使用 SQL 将文本文件导入通用数据库

python - 如何在Python中将类导入到同一文件中的其他类中

Python 循环导入, `from lib import module` 与 `import lib.module`

python - 等到嵌套的 python 脚本结束,然后再继续当前的 python 脚本

module - 我可以用 1 个模块实现多种模块类型吗?

python - 从父文件夹导入模块