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

标签 python macos unix terminal environment-variables

<分区>

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

在 macOS Mojave 上

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

输出:

False
exists

最佳答案

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

from os.path import expanduser
home = expanduser("~")

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

关于Python2.7 ~波浪号在路径中无法识别为主目录 macOs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53526381/

相关文章:

linux - 查找文件名中没有空格的文件

python - 如何防止进程在 KeyboardInterrupt 上终止?

python - 检查变量的输入是否为xx.xx.xxxx格式

python - 在 Python 中根据已排序的词汇表有效匹配单词

python - 气流 initdb : undefined symbol: Py_GetArgcArgv

macos - MacOS Catalina 上的 sed/gsed 无法按预期与 star 一起工作

c - 为什么我的子进程没有给我 "correct"结果?

python - 返回 peewee ORM 中分组项目的计数

macos - 连接耳机后能否将声音发送到扬声器?

python - 如何将 Python 虚拟环境转移给其他用户?