Python2.7 ~ 代字号在路径中无法识别为 macOs 主目录

buz*_*z11 4 python unix macos terminal environment-variables

在某些时候,波形符 ~ 不再被识别为我的主目录,仅在 Python 中如此。〜仍然可以在终端中使用,所以我不确定发生了什么,但任何有关如何修复它的见解都会为我节省一些打字时间,谢谢!

在 macOS Mojave 上

import os
tilde = '~'
print(os.path.exists(tilde))
os.system("if test -d ~; then echo 'exists'; fi")
Run Code Online (Sandbox Code Playgroud)

输出:

False
exists
Run Code Online (Sandbox Code Playgroud)

Abt*_*Pst 5

~由操作系统而不是 Python 解释。从 Python 脚本中使用它的方法是:

from os.path import expanduser
home = expanduser("~")
Run Code Online (Sandbox Code Playgroud)

现在home将具有由 表示的路径~