简体   繁体   English

如何在绝对导入的子目录中运行python脚本

[英]How to run a python script that's inside a subdirectory which has absolute imports

I have the following directory structure and files: 我具有以下目录结构和文件:

├── a
│   ├── b
│   │   ├── b.py
│   └── c
│       ├── c.py
└── main.py

# main.py
from a.b import b
print('i am main')

# a/b/b.py
from a.c import c
print('i am b')

# a/c/c.py
print('i am c')

The following works just fine and is expected. 以下工作正常,并且可以预期。

» python3 main.py
i am c
i am b
i am main

However, if I go inside the directory a/b and run 但是,如果我进入目录a/b并运行

python3 b.py

I get: 我得到:

» python3 b.py
Traceback (most recent call last):
  File "b.py", line 1, in <module>
    from a.c import c
ModuleNotFoundError: No module named 'a'

And if I try to run it from the root of the project I get 如果我尝试从项目的根目录运行它,我会得到

» python3 a/b/b.py
Traceback (most recent call last):
  File "a/b/b.py", line 1, in <module>
    from a.c import c
ModuleNotFoundError: No module named 'a'

It makes sense that it can't find the module which is one level above the directory but how would one run a/b/b.py script in this scenario? 找不到目录上一级的模块是有意义的,但是在这种情况下如何运行a/b/b.py脚本?

I'd still like a better explanation on why this works. 我仍然想更好地解释它为什么起作用。 But I got a hint for this from this answer. 但是我从这个答案中得到了一个提示。 You can run 你可以跑

python3 -m a.b.b 

to run b.py which is inside a/b/ directory. 运行位于a/b/目录中的b.py

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

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