对于新写的代码,最好不要用下面的方式,而是在配置文件中定义BASE_PATH
,路径的连接都使用os.path.join
,这样代码自然就是跨平台的,对于遗留代码,可以通过下面的to_os_path
快速提供平台兼容性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import sys import os import re
def to_os_path(path): if sys.platform == 'linux': return to_linux_path(path) else: return to_windows_path(path)
def to_linux_path(path): m = re.match(r"\\\\\d+\.\d+\.\d+\.(\d+)\\([^\\])", path) if m: return '/mnt/' + m.group(1) + m.group(2) + path[m.span()[1] : ].replace('\\', '/') m = re.match(r"([a-zA-Z]):\\", path) if m: return '/mnt/' + m.group(1) + '/' + path[m.span()[1] : ].replace('\\', '/')
return path.replace('\\', '/')
def to_windows_path(path): m = re.match(r"/mnt/(\d+)([^\\])", path) if m: return r"\\192.168.1.{}\{}{}".format(m.group(1), m.group(2), path[m.span()[1] : ].replace('/', '\\')) m = re.match(r"/mnt/([a-zA-Z])\b", path) if m: return m.group(1) + ":" + path[m.span()[1] : ].replace('/', '\\') return path.replace('/', '\\')
|