如何防止 Python 在当前工作目录中搜索模块?

How to prevent Python from search the current working directory for modules?

我有一个导入 datetime 模块的 Python 脚本。它运行良好,直到有一天我可以 运行 它在一个目录中,该目录有一个名为 datetime.py 的 Python 脚本。当然,有几种方法可以解决这个问题。首先,我 运行 脚本在一个不包含脚本 datetime.py 的目录中。其次,我可以将 Python 脚本重命名为 datetime.py。但是,这两种方法都不是完美的方法。假设一个人发布了一个 Python 脚本,他永远不知道用户会在哪里 运行 Python 脚本。另一个可能的修复是防止 Python 在当前工作目录中搜索模块。我试图从 sys.path 中删除空路径 (''),但它在交互式 Python shell 中有效,但在 Python 脚本中无效。调用的 Python 脚本仍然在当前路径中搜索模块。请问有什么方法可以禁止Python在当前路径中搜索模块吗?

if __name__ == '__main__':
    if '' in sys.path:
        sys.path.remove('')
    ...

请注意,即使我将以下代码放在脚本的开头,它也不起作用。

import sys
if '' in sys.path:
    sys.path.remove('')

下面是 Whosebug 上的一些相关问题。

Removing path from Python search module path

initialization of multiarray raised unreported exception python

您确定 Python 在 当前目录 中搜索该模块,而不是在 脚本目录 中搜索该模块吗?我认为 Python 不会将当前目录添加到 sys.path,除了一种情况。这样做甚至可能存在安全风险(类似于在 UNIX PATH 上使用 .)。

根据 documentation:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first

因此,'' 作为当前目录的表示仅在来自解释器的 运行 时发生(这就是为什么您的交互式 shell 测试有效)或者如果脚本是从标准输入(类似于 cat modquest/qwerty.py | python)。通常,运行宁 Python 脚本的 'normal' 方式也不是。

我猜你的 datetime.py 与你的实际脚本并排放置(在 脚本目录 上),而且恰好你是运行从该目录(即 脚本目录 == 当前目录)中安装脚本。

如果这是实际情况,并且您的脚本是独立的(意味着只有一个文件,没有本地导入),您可以这样做:

sys.path.remove(os.path.abspath(os.path.dirname(sys.argv[0])))

但请记住,一旦脚本变大并且您将其拆分为多个文件,这将在未来对您产生不利影响,却只花了几个小时试图弄清楚为什么它不导入本地文件.. .

另一种选择是使用 -I,但这可能有点矫枉过正:

-I

Run Python in isolated mode. This also implies -E and -s. In isolated mode sys.path contains neither the script’s directory nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too. Further restrictions may be imposed to prevent the user from injecting malicious code.