简体   繁体   English

从其他目录执行python文件

[英]Execute a python file from different directory

I try to understand how to split up python files belonging to the same project in different directories. 我尝试了解如何在不同目录中拆分属于同一项目的python文件。 If I understood it right I need to use packages as described here in the documentation . 如果我理解正确,则需要使用文档此处所述的软件包。

So my structure looks like this: 所以我的结构看起来像这样:

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

with empty __init__.py files and 空的__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()

Now I expect that when I execute B/fileB.py I get "Hello from A" , but instead I get the following error: 现在,我希望在执行B/fileB.py得到"Hello from A" B/fileB.py "Hello from A" ,但会出现以下错误:

ModuleNotFoundError: No module named 'A'

What am I doing wrong? 我究竟做错了什么?

One way to solve this is to add module A into the path of fileB.py by adding 解决此问题的一种方法是通过添加将模块A添加到fileB.py的路径中

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

to the top of fileB.py. 到fileB.py的顶部。

Your problem is the same as: 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. TL; DR:由于模块不是软件包的一部分,因此您无法从执行的文件中进行相对导入。

As main: 作为主要:

python B/fileB.py

Output: 输出:

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

As a module (not main): 作为模块(不是主要模块):

python -m B.fileB

Output: 输出:

hello from A

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM