脚本目录不包括在系统路径当有人在美国的时候

2024-09-30 00:35:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当我使用ActivePython时,Python脚本可以完美地工作。{不过,当我得到下面的错误时,我使用下面的错误。在

ModuleNotFoundError: No module named 'pyWhich'

我把行为的差异追溯到系统路径在嵌入式发行版中设置了veritable。在

在ActivePython中,脚本工作的环境,其中的第一个条目系统路径是包含脚本的目录。在嵌入式发行版中,没有包含脚本的目录项。在

嵌入式发行版使用一个\u pth文件来设置搜索路径. 我使用的是默认的.u pth文件,为了您的方便,我在下面提供了这个文件。在

^{pr2}$

我的问题是,要告诉Python将包含我运行的任何脚本的目录添加到我的u pth文件中,我需要添加什么魔力咒语系统路径所以我的脚本将与嵌入式发行版一起工作。path configuration files上的文档似乎不包含此信息。在


Tags: 模块文件no路径目录脚本系统错误
2条回答

我仍然希望有一个神奇的咒语可以添加到我的u pth文件中,上面写着“请将包含我运行的任何脚本的目录放入目录”搜索路径“所以我不必修改我所有的脚本。然而,有可能根本不存在这种神奇的咒语。在

我发现下面的魔法咒语,当添加到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 Which project。在

你试过了吗系统路径追加('C:/documents/folder/blah…') (具有正确的文件夹位置ofc)

相关问题 更多 >

    热门问题