从不同的目录执行python文件

2024-09-30 22:14:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解如何将属于同一项目的python文件拆分到不同的目录中。如果我理解正确,我需要使用here in the documentation所描述的包。你知道吗

所以我的结构是这样的:

.
├── A
│   ├── fileA.py
│   └── __init__.py
├── B
│   ├── fileB.py
│   └── __init__.py
└── __init__.py

有空的__init__.py文件和

$ cat A/fileA.py 
def funA():
    print("hello from A")

$ cat B/fileB.py 
from A.fileA import funA

if __name__ == "__main__":
    funA()

现在我希望在执行B/fileB.py时得到"Hello from A",但得到的却是以下错误:

ModuleNotFoundError: No module named 'A'

我做错什么了?你知道吗


Tags: 文件the项目infrompy目录here
2条回答

您的问题与:Relative imports for the billionth time相同

TL;DR: you can't do relative imports from the file you execute since main module is not a part of a package.

作为主要:

python B/fileB.py

输出:

Traceback (most recent call last):
  File "p2/m2.py", line 1, in <module>
    from p1.m1 import funA
ImportError: No module named p1.m1

作为模块(非主模块):

python -m B.fileB

输出:

hello from A

解决这个问题的一种方法是将模块A添加到文件b.py通过添加

import sys
sys.path.insert(0, 'absolute/path/to/A/')

到山顶文件b.py. 你知道吗

相关问题 更多 >