编程语言
首页 > 编程语言> > 如果import语句只包含文件名,python如何找到模块文件?

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

作者:互联网

我看到Python代码使用import sys导入模块或导入mymodule

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

解决方法:

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

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. 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:

  • 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.包含正在运行的脚本的目录位于搜索路径的开头,位于标准库路径之前.这意味着将加载该目录中的脚本,而不是库目录中的同名模块.除非有意更换,否则这是一个错误.有关更多信息,请参见标准模块一节

有关“特定于安装的默认值”的信息,请参阅the site module上的文档.

标签:pythonpath,python,python-import,python-module
来源: https://codeday.me/bug/20190917/1809208.html