简体   繁体   English

如果import语句仅包含文件名,python如何找到模块文件?

[英]How does python find a module file if the import statement only contains the filename?

Everywhere I see Python code importing modules using import sys or import mymodule 我到处都可以看到使用import sysimport mymodule import sys Python代码的模块

How does the interpreter find the correct file if no directory or path is provided? 如果没有提供目录或路径,解释器如何找到正确的文件?

http://docs.python.org/3/tutorial/modules.html#the-module-search-path http://docs.python.org/3/tutorial/modules.html#the-module-search-path

6.1.2. 6.1.2。 The Module Search Path 模块搜索路径

When a module named spam is imported, the interpreter first searches for a built-in module with that name. 导入名为spam的模块时,解释器首先搜索具有该名称的内置模块。 If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path . 如果找不到,它将在变量sys.path给出的目录列表中搜索名为spam.py的文件。 sys.path is initialized from these locations: sys.path从以下位置初始化:

  • The directory containing the input script (or the current directory when no file is specified). 包含输入脚本的目录(如果未指定文件,则为当前目录)。
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH ). PYTHONPATH (目录名称列表,语法与shell变量PATH )。
  • The installation-dependent default. 取决于安装的默认值。

Note: On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed. 注意:在支持符号链接的文件系统上,在遵循符号链接之后计算包含输入脚本的目录。 In other words the directory containing the symlink is not added to the module search path. 换句话说,包含符号链接的目录不会添加到模块搜索路径中。

After initialization, Python programs can modify sys.path . 初始化之后,Python程序可以修改sys.path The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. 包含正在运行的脚本的目录位于搜索路径的开始,在标准库路径之前。 This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. 这意味着将加载该目录中的脚本,而不是库目录中相同名称的模块。 This is an error unless the replacement is intended. 除非打算进行更换,否则这是一个错误。 See section Standard Modules for more information. 有关更多信息,请参见标准模块部分。

For information on the "installation-specific default", see documentation on the site module . 有关“特定于安装的默认设置”的信息,请参阅site模块文档。

Also, you can see what the current path is by using the sys module 另外,您可以使用sys模块查看当前路径是什么

import sys
print(sys.path)

它使用设置为环境变量的PYTHONPATH查找包(包含__init__.py文件的文件夹)和模块(或者,如果已经加载一次,则从sys.modules检索模块对象)。

Python has a path variable just like the one you have inside your terminal. Python具有一个路径变量,就像您在终端中拥有的那样。 Python looks for modules in folders inside that path, or in the folder where your program is located. Python在该路径内的文件夹中或程序所在的文件夹中查找模块。

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

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