为何subprocess可识别~/路径,os.path.exists却不行?求Python处理方法
Python中~/路径的访问问题与解决方法
问题重现
Shell操作步骤:
mkdir ~/mnt touch ~/mnt/test.txt ls ~/mnt
执行结果:
test.txt
Python3测试代码:
import os import subprocess print(os.path.exists('~/mnt')) print(os.path.exists(os.path.abspath('~/mnt'))) subprocess.call('ls ~/mnt', shell=True)
执行结果:
False False test.txt 0
问题原因
~是Shell专属的特殊通配符,只有Shell在解析命令时,才会自动将其替换为当前用户的家目录(比如/home/username)。- 当
subprocess.call()设置shell=True时,会启动一个完整的Shell进程来执行命令,此时Shell会处理~并替换为实际路径,因此ls ~/mnt能正常找到目标目录。 - 而
os.path模块的函数(如exists()、abspath())不会调用Shell,它们会把~当作普通路径字符处理,实际查找的是当前工作目录下名为~的子目录中的mnt,自然找不到对应路径,所以返回False。
正确处理~/路径的方法
方法1:使用os.path.expanduser()
该函数专门用于解析路径中的~,将其替换为当前用户的家目录:
import os target_path = os.path.expanduser('~/mnt') print(os.path.exists(target_path)) # 输出True
方法2:使用pathlib模块(Python3.4+推荐)
pathlib是Python官方推荐的现代路径处理库,其Path对象的expanduser()方法同样可以处理~:
from pathlib import Path target_path = Path('~/mnt').expanduser() print(target_path.exists()) # 输出True
内容的提问来源于stack exchange,提问作者Jerin Antony
相关产品推荐
相关产品推荐

