简体   繁体   English

为什么 pathlib.Path(__file__).parent.parent 对我的工作目录敏感?

[英]Why is pathlib.Path(__file__).parent.parent sensitive to my working directory?

I have a script that's two directories down.我有一个包含两个目录的脚本。

❯ tree
.
└── foo
    └── bar
        └── test.py
❯ cd foo/bar
❯ cat test.py

    from pathlib import Path
    print(Path(__file__).parent)
    print(Path(__file__).parent.parent)

When I run it from the directory that contains it, PathLib thinks that the file's grandparent is the same as its parent.当我从包含它的目录运行它时,PathLib 认为文件的祖父母与其父文件相同。

❯ python test.py

    . # <-- same
    . # <-- directories

But when I run it from the top level, PathLib behaves correctly.但是当我从顶层运行它时,PathLib 行为正确。

❯ cd ../..
❯ python foo/bar/test.py

    foo/bar # <-- different
    foo     # <-- directories

Am I misunderstanding something about PathLib's API, or is something else causing its output to be sensitive to my working directory?我对 PathLib 的 API 有什么误解,还是其他原因导致它的 output 对我的工作目录敏感?

You need to call Path.resolve() to make your path absolute (a full path including all parent directories and removing all symlinks)您需要调用Path.resolve()以使您的路径成为绝对路径(包括所有父目录并删除所有符号链接的完整路径)

from pathlib import Path
print(Path(__file__).resolve().parent)
print(Path(__file__).resolve().parent.parent)

This will cause the results to include the entire path to each directory, but the behaviour will work wherever it is called from这将导致结果包含每个目录的整个路径,但无论从何处调用该行为都将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM