1

以下使用 Path() 的代码正在丢失相关信息:

    src_file=inspect.getfile(CompileTypeData)
    logger.debug(f'SRC_FILE: {src_file}')
    src_path = Path(src_file).resolve()
    logger.debug(f'SRC_PATH: {src_path}')
    logger.debug(f'SRC_DIRNAME: {src_path.parent}')

产生这个:

 DEBUG:from_project_types_file:SRC_FILE: ../../build_compile_mod/compile_type.py
 DEBUG:from_project_types_file:SRC_PATH: /build_compile_mod/compile_type.py
 DEBUG:from_project_types_file:SRC_DIRNAME: /build_compile_mod

我的相对路径发生了什么?我的理解是 resolve() 应该使它成为绝对路径而不是丢失数据。

4

2 回答 2

0

my_path.resolve()接受一个附加参数,strict默认为False. 如果设置为,则如果路径无法解析为绝对路径True,则会引发 a 。FileNotFoundError这可用于评估 pathlib 是否有足够的数据来从您获得的字符串创建绝对路径inspect.getfile()

inspect.getfile()并不总是返回绝对路径,但您始终可以使用 转换该路径os.path.realpath(inspect.getfile(obj)),或将Path.relative_to(...)方法与 . 结合使用os.path.realpath(__file__)

于 2018-04-10T18:47:36.193 回答
0

相对路径和示例sys.path.insert

如果您在运行脚本时将相对路径放入sys.path使用 sys.path.insert和更改目录,那么您将得到错误的答案,尝试使用__file__或从它派生的任何内容。

假设我们有这个:

 /tmp/test1
 /tmp/test2
 /tmp/test2/mymod.py
 /tmp/rundir/rundir2

所以我们 CD 到 `/tmp/test2/ 并启动脚本。

% cd /tmp/test2

现在我们在 Test2 中创建这个脚本,它定义了 show_path()哪个找到路径mymod.py 并打印它。

请注意,sys.path.insert使用相对路径这就是问题所在。

 import sys
 sys.path.insert(0,'../test1')
 from mymod import *
 import inspect  
 from pathlib import Path

 def show_path():
     myClassFile=inspect.getfile(MyClass)
     print(Path(myClassFile).resolve())

所以现在我们运行我们的脚本。它从其中开始,/tmp/test2/ 然后更改目录并运行show_path().

请注意,show_path()由于相对路径,它指向无处。

 import os
 os.chdir('/tmp/rundir/rundir2')
 show_path()

这给出了以下不正确的输出。

/private/tmp/rundir/test1/mymod.py
于 2018-04-10T18:55:51.223 回答