简体   繁体   English

为什么我需要包含 sys.path.append 来使用 Python 3.6 导入模块而我的大学不需要?

[英]Why do I need to include sys.path.append to import a module with Python 3.6 and my colleges doesn't need?

I have been facing a weird situation for some months now.几个月来,我一直面临着一个奇怪的情况。

In the several codes I have been working, to import a module in python 3.6.9, Ubuntu 18.04, such as:在我一直在工作的几个代码中,在python 3.6.9、Ubuntu 18.04中导入一个模块,例如:

import src.Modules.ABC.DC as DC

I do need to include sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..')) but all my colleges at work using the same code and virtual environment just does not need that line.我确实需要包括sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..'))但我所有的大学都在使用相同的代码和虚拟环境只是不需要那一行。

If it helps, in the terminal, if I do not include that line it returns:如果有帮助,在终端中,如果我不包含该行,它将返回:

ModuleNotFoundError: No module named 'src'

Consequently, my questions are:因此,我的问题是:

1-Why do I need to include that line and in a different computer I does not need? 1-为什么我需要在另一台我不需要的计算机中包含该行?

2-Do you suggested to always include that line to have a more reliable code? 2-您是否建议始终包含该行以获得更可靠的代码?

The folder structure is something like:文件夹结构类似于:

Myproject/src/Modules/ABC/DE

Myproject/tests/Modules/ABC/test_DE

I created a virtual env at Myproject, at src, tests and so on.我在 Myproject、src、tests 等创建了一个虚拟环境。 And it returns always the same.它返回始终相同。 When I run without a venv it also returns the same problem.当我在没有 venv 的情况下运行时,它也会返回同样的问题。 The python command I use is我使用的python命令是

python3 tests/Modules/ABC/test_DE.py

This is just annoying since I always need to remove that line to request a merge.这很烦人,因为我总是需要删除该行来请求合并。

Just set the PYTHONPATH environment variable to (the full path to) Myproject .只需将PYTHONPATH环境变量设置为(完整路径) Myproject That tells Python where to find modules to import, and it works regardless of which directory you run the script from.这告诉 Python 在哪里可以找到要导入的模块,并且无论您从哪个目录运行脚本,它都可以工作。 This avoids the need to modify sys.path .这避免了修改sys.path的需要。

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

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