如果import语句只包含文件名,python如何找到模块文件? [英] How does python find a module file if the import statement only contains the filename?

查看:56
本文介绍了如果import语句只包含文件名,python如何找到模块文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在任何地方看到 Python 代码使用 import sysimport mymodule

Everywhere I see Python code importing modules using import sys or import mymodule

如果没有提供目录或路径,解释器如何找到正确的文件?

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

6.1.2.模块搜索路径

6.1.2. The Module Search Path

当导入名为 spam 的模块时,解释器首先搜索具有该名称的内置模块.如果没有找到,它将在变量 sys.path 给出的目录列表中搜索名为 spam.py 的文件.sys.path 从以下位置初始化:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. 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 is initialized from these locations:

  • 包含输入脚本的目录(或未指定文件时的当前目录).
  • PYTHONPATH(目录名称列表,语法与shell变量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).
  • 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.

初始化后,Python 程序可以修改sys.path.包含正在运行的脚本的目录位于搜索路径的开头,在标准库路径之前.这意味着将加载该目录中的脚本而不是库目录中的同名模块.这是一个错误,除非更换是有意的.有关详细信息,请参阅标准模块部分.

After initialization, Python programs can modify 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.

有关特定于安装的默认设置"的信息,请参阅有关 site 模块.

For information on the "installation-specific default", see documentation on the site module.

这篇关于如果import语句只包含文件名,python如何找到模块文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆