7

我正在尝试解决一个与在我编写的 Python 脚本中导入模块相关的奇怪问题。实现该模块的文件与主要 Python 脚本位于同一目录中。

当我使用 ActivePython 时,Python 脚本可以完美运行。但是,当我使用嵌入式分发时,我收到以下错误。

ModuleNotFoundError: No module named 'pyWhich'

我已经将行为差异追溯到嵌入式分发中设置 sys.path 名副其实的方式。

在 ActivePython(我的脚本工作的环境)中,sys.path 中的第一个条目是包含脚本的目录。在嵌入式发行版中,没有包含脚本的目录条目。

Embedded Distribution 使用 _pth 文件来设置 sys.path。我正在使用默认的 ._pth 文件,为方便起见,我将其包含在下面。

python36.zip
.

# Uncomment to run site.main() automatically
#import site

我的问题是,我需要在我的 _pth 文件中添加什么神奇的咒语来告诉 Python请将包含我运行的任何脚本的目录放在 sys.path 中,以便我的脚本可以与嵌入式发行版一起使用。路径配置文件的文档似乎不包含此信息。

4

3 回答 3

2

我仍然希望有一个神奇的咒语,我可以添加到我的 _pth 文件中,上面写着“请将包含我在 sys.path 中运行的任何脚本的目录”,这样我就不必修改我的所有脚本。然而,有可能不存在这样的魔法咒语。

我发现将以下魔法咒语添加到 Python 脚本中时,可以达到预期的效果。而且,与您可能在野外发现的其他解决方案不同,这个解决方案将在 cx_Freeze 和 IDLE 的上下文中以及在基于简单文件的解决方案不起作用的任何其他上下文中工作。

import inspect
import os
import sys

# Add script directory to sys.path.
# This is complicated due to the fact that __file__ is not always defined.

def GetScriptFile():
    """Obtains the full path and file name of the Python script."""
    if hasattr(GetScriptFile, "file"):
        return GetScriptFile.file
    ret = ""
    try:
        # The easy way. Just use __file__.
        # Unfortunately, __file__ is not available when cx_freeze is used or in IDLE.
        ret = os.path.realpath(__file__)
    except NameError:
        # The hard way.
        if len(sys.argv) > 0 and len(sys.argv[0]) > 0 and os.path.isabs(sys.argv[0]):
            ret = os.path.realpath(sys.argv[0])
        else:
            ret = os.path.realpath(inspect.getfile(GetScriptFile))
            if not os.path.exists(ret):
                # If cx_freeze is used the value of the ret variable at this point is in
                # the following format: {PathToExeFile}\{NameOfPythonSourceFile}. This
                # makes it necessary to strip off the file name to get the correct path.
                ret = os.path.dirname(ret)
    GetScriptFile.file = ret
    return GetScriptFile.file

def GetScriptDirectory():
    """Obtains the path to the directory containing the script."""
    if hasattr(GetScriptDirectory, "dir"):
        return GetScriptDirectory.dir
    module_path = GetScriptFile()
    GetScriptDirectory.dir = os.path.dirname(module_path)
    return GetScriptDirectory.dir

sys.path.insert(0, GetScriptDirectory())

顺便说一句,如果您希望看到这一点,我已经在我的Python 哪个项目中实现了它。

于 2018-04-26T00:17:46.603 回答
0

您是否尝试过 sys.path.append('C:/documents/folder/blah...') (正确的文件夹位置为 c)

于 2018-04-25T14:06:21.483 回答
0

我的解决方案是删除此文件:

python39._pth

这允许 Pip 工作,也允许import来自同一目录。或者你可以得到这个:

https://nuget.org/packages/python

单击“下载包”,您可以像解压缩 Zip 文件一样进行解压。

于 2020-12-17T00:26:42.933 回答