os.path.realpath(__ file__)未返回预期路径

问题描述 投票:0回答:1

我以如下方式运行脚本:

python tools/debug_tool.py

我在脚本内打印__file__,没关系:

tools/debug_tool.py

但是os.path.realpath(__file__)错误:

/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/Resources/tools/debug_tool.py

os.path.abspath(__file__)的相同结果

为什么会这样?

os.path.realpath(__file__)的预期结果是:

/Users/my_user/my_project/tools/debug_tool.py

此外,当我将文件保存到当前目录时,例如cv2.imwrite('temp.png', image),它也会将文件保存到/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/Resources/

python macos environment
1个回答
1
投票

os.path.realpath应该解析符号链接并返回规范路径:

返回指定文件名的规范路径,消除任何路径中遇到的符号链接(如果操作系统)。

注意,您还需要解析文件的目录:

os.path.realpath

如果您在不解析符号链接的情况下查找绝对路径,则需要使用os.path.realpath(os.path.dirname(__file__))

返回路径名路径的标准化绝对化版本。在大多数平台,相当于调用函数os.path.abspath为如下:os.path.abspath

normpath()

应生成所需的输出:

normpath(join(os.getcwd(), path))
© www.soinside.com 2019 - 2024. All rights reserved.