简体   繁体   English

Python 如何跟踪要导入的库(目录)?

[英]How does Python keep track of libraries (directories) to import?

I have two slightly different branches of Python 3 code on my computer.我的计算机上有两个略有不同的 Python 3 代码分支。 I am frequently switching back and forth between them.我经常在它们之间来回切换。 Both contain slightly modified files and directories that are named the same way.两者都包含稍微修改过的文件和目录,它们的命名方式相同。 The code in each directory imports code from a subdirectory, eg "from ldm.util import instantiate_from_config", where "ldm" is a subdirectory of the directory I'm currently in, and "util.py" is a file in "ldm."每个目录中的代码从一个子目录中导入代码,例如“from ldm.util import instantiate_from_config”,其中“ldm”是我当前所在目录的一个子目录,“util.py”是“ldm.py”中的一个文件。 “

Python keeps getting confused when I import and using the "util.py" and "ldm" directory from the other branch.当我从其他分支导入和使用“util.py”和“ldm”目录时,Python 一直感到困惑。 Neither branch is on the Windows PATH or PYTHONPATH.这两个分支都不在 Windows PATH 或 PYTHONPATH 上。 I can trick Python by temporarily renaming the directory I don't want to use, but I want to understand: how is Python remembering that this other directory exists to go import it?我可以通过临时重命名我不想使用的目录来欺骗 Python,但我想了解:Python 是如何记住这个其他目录存在的,以便 go 导入它? How can I tell Python that if a folder is a subdirectory of the folder I'm currently in, that's the version I want it to import?我如何告诉 Python,如果一个文件夹是我当前所在文件夹的子目录,那就是我希望它导入的版本?

I think I found the answers:我想我找到了答案:

  1. "The first thing Python will do is look up the name abc in sys.modules. This is a cache of all modules that have been previously imported." “Python 会做的第一件事是在 sys.modules 中查找名称 abc。这是以前导入的所有模块的缓存。”
  2. "The syntax of a relative import depends on the current location as well as the location of the module, package, or object to be imported." “相对导入的语法取决于当前位置以及要导入的模块的位置,package 或 object。” So it needs a "."所以它需要一个“。” beforehand to tell it to use something from the current location.事先告诉它使用当前位置的东西。 Example: "from.subpackage1.module5 import function2" from https://realpython.com/absolute-vs-relative-python-imports/示例:来自https://realpython.com/absolute-vs-relative-python-imports/的“from.subpackage1.module5 import function2”

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

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