如何检测Windows网络路径以避免脚本执行异常?
判断Windows网络路径(UNC路径)的方法
问题场景
编写脚本运行用户提供目录中的Windows可执行文件时,发现切换到网络路径(UNC路径)后,执行命令会失败:
>>> import os >>> os.chdir(r'\\server\share\folder') # 实际路径类似但不同 >>> os.getcwd() '\\\\server\\share\\folder' >>> os.system('echo %CD%') '\\server\share\folder' CMD.EXE was started with the above path as the current directory. UNC paths are not supported. Defaulting to Windows directory. C:\Windows 0
需要在脚本中提前判断用户提供的路径是否为网络路径,避免后续执行失败。
解决方案
方法1:路径前缀匹配
Windows的UNC网络路径标准格式以\\开头,可通过标准化路径后检查前缀实现判断:
import os def is_unc_path(path): normalized_path = os.path.normpath(path) return normalized_path.startswith('\\\\')
调用示例:
print(is_unc_path(r'\\server\share\folder')) # 输出 True print(is_unc_path(r'c:\work\project42')) # 输出 False
方法2:利用pathlib模块(Python 3.4+)
pathlib对路径的封装更直观,可直接通过drive属性判断:
from pathlib import Path def is_unc_path(path): path_obj = Path(path) return path_obj.drive.startswith('\\\\')
调用示例:
print(is_unc_path(Path(r'\\server\share\folder'))) # 输出 True print(is_unc_path(Path(r'c:\work\project42'))) # 输出 False
方法3:Windows API验证(需pywin32)
若要处理更复杂的场景(比如路径存在但映射过的网络驱动器),可调用Windows原生API判断:
import win32file def is_unc_path(path): try: attrs = win32file.GetFileAttributesW(path) # 网络路径会带有重解析点和目录属性 return (attrs & win32file.FILE_ATTRIBUTE_REPARSE_POINT) and (attrs & win32file.FILE_ATTRIBUTE_DIRECTORY) except Exception: # 路径不可访问时回退到前缀判断 import os normalized_path = os.path.normpath(path) return normalized_path.startswith('\\\\')
使用前需安装pywin32:
pip install pywin32
内容的提问来源于stack exchange,提问作者anatolyg
相关产品推荐
相关产品推荐

