use*_*401 8 python django environment-variables pathlib
我需要创建一个以当前目录开头的相对路径“.” 点
例如,在 Windows 中“.\envs\.some.env”或其他地方的“./envs/.some.env”
我想使用 pathlib 来做到这一点。找到了解决方案,但它有一个笨拙的替换语句。有没有更好的方法使用 pathlib 来做到这一点?
用法是 django-environ,目标是支持多个 env 文件。工作文件夹包含一个 envs 文件夹,该文件夹中包含多个 env 文件。
import environ
from pathlib import Path
import os
domain_env = Path.cwd()
dotdot = Path("../")
some_env = dotdot / "envs" / ".some.env"
envsome = environ.Env()
envsome.read_env(envsome.str(str(domain_env), str(some_env).replace("..", ".")))
print(str(some_env))
print(str(some_env).replace("..", "."))
dot = Path("./") # Path(".") gives the same result
some_env = dot / "envs" / ".some.env"
print(str(some_env))
Run Code Online (Sandbox Code Playgroud)
在 Windows 上给出:
..\envs\.some.env
.\envs\.some.env
envs\.some.env
Run Code Online (Sandbox Code Playgroud)
我能找到的最好的是(正如问题\xe2\x80\x99s 评论中metatoaster所建议的那样):
\nos.path.join(".", some_env)\nRun Code Online (Sandbox Code Playgroud)\n其中some_env可以是字符串或bytes(自 Python\xc2\xa03.6 起)任何类似路径的对象(这意味着您不必再将Path对象转换为字符串)。
由于有些人想知道为什么这可能有用:
\nfoo.sh不能被调用foo.sh(除了.is in时$PATH),而必须使用 来调用./foo.sh。require()存在差异。foo./foo-quiet. ExifTool 不遵守\xe2\x80\x99t 的 Unix 约定,即有一个--参数表示所有以下参数都不是选项,其作者的官方建议是 \xe2\x80\x9c[p]ut 目录名称如果文件名以破折号\xe2\x80\x9d 开头,则在文件名之前。这是一个多平台的想法:
import ntpath
import os
import posixpath
from pathlib import Path, PurePosixPath, PureWindowsPath
def dot_path(pth):
"""Return path str that may start with '.' if relative."""
if pth.is_absolute():
return os.fsdecode(pth)
if isinstance(pth, PureWindowsPath):
return ntpath.join(".", pth)
elif isinstance(pth, PurePosixPath):
return posixpath.join(".", pth)
else:
return os.path.join(".", pth)
print(dot_path(PurePosixPath("file.txt"))) # ./file.txt
print(dot_path(PureWindowsPath("file.txt"))) # .\file.txt
print(dot_path(Path("file.txt"))) # one of the above, depending on host OS
print(dot_path(Path("file.txt").resolve())) # (e.g.) /path/to/file.txt
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3997 次 |
| 最近记录: |