【问题标题】:Does import look in the current working directory before the path? or the path then the cwd?导入是否在路径之前查看当前工作目录?或者路径然后是cwd?
【发布时间】:2018-08-31 07:03:58
【问题描述】:

以下哪项描述了from [...] import [...] 的行为?

  • cwd first:先看工作目录,再看路径
  • 先看路径:先看路径,再看工作目录

考虑以下脚本:

改变路径

sys.path.insert(0, 'E:\\demo_dir\\example_dir\\eg_dir\\test_dir\\')
from src import name
sys.path.pop(0)

更改 Cwd

old_cwd = os.getcwd()
os.chdir('E:\\demo_dir\\example_dir\\eg_dir\\test_dir\\')
from src import name
os.chdir(old_cwd)

组合脚本

old_cwd = os.getcwd(); os.chdir('E:\\demo_dir\\example_dir\\eg_dir\\test_dir\\')
sys.path.insert(0, 'E:\\demo_dir\\example_dir\\eg_dir\\test_dir\\')

from src import name

os.chdir(old_cwd)
sys.path.pop(0)

假设在 sys.path 和 cwd 中都有一个名为 src 的东西, 并且系统路径中的src与cwd中的src不一样

我们只是从 sys.path 导入 src 吗?还是来自 cwd 的 src

【问题讨论】:

标签: python python-3.x import python-import sys


【解决方案1】:

只有sys.path 用于搜索要作为模块加载的文件; Python 不会查看sys.path 之外的其他目录。¹仅当''(空字符串)在路径中时才会搜索当前工作目录²,因此如果当前工作目录中都有src.py和路径中的另一个目录,将被加载的目录是路径中的第一个。

当你直接运行Python解释器时(包括你运行python -m modulename时)你会发现''自动出现在sys.path的前面。这是standard Python behaviour。然而,如果你直接运行一个脚本(例如,只输入myscript,它以#!/usr/bin/env python开头)而不是脚本的目录(例如,/usr/bin,如果你的shell找到并运行/usr/bin/myscript)将被添加到前面的路径。 (脚本本身当然可以在运行时将更多项目添加到路径的前面。)


¹ 实际上,这并不完全正确。 import 首先在sys.meta_path 中查询查找器。那些可以看任何他们喜欢的地方,甚至可能不使用sys.path
² 你也可以在路径中使用../. 或各种类似的想法,虽然这样变得棘手只是自找麻烦。

【讨论】:

  • 这是真的,但您应该添加一些细节,说明何时/为什么 ''sys.path 的第一个元素以及何时/为什么不是。
  • @wim 好主意;我已经这样做了。如果可以改进,请随意编辑。
  • 是的,LGTM +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 2021-02-24
  • 1970-01-01
  • 2012-04-12
  • 2015-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多