Convert POSIX->WIN path, in Cygwin Python, w/o calling cygpath -
i use python script, running in cygwin build of python, create commands issued native windows utilities (not cygwin-aware). requires conversion of path parameters posix win form before issuing command.
calling cygpath utility nicest way this, since uses cygwin it's there do, it's little horrifying (and slow).
i'm running cygwin build of python - code conversion present. seems there should cygwin/python specific extension gives me hook capability, directly in python, without having fire whole new process.
this possible calling cygwin api using ctypes. below code works me–i using 64-bit cygwin dll version 2.5.2 on windows 2012, , works on cygwin versions of both python 2.7.10 , python 3.4.3.
basically call cygwin_create_path cygwin1.dll perform path conversion. function allocates memory buffer (using malloc) containing converted path. need use free cygwin1.dll release buffer allocated.
note xunicode below poor man's alternative six (a python 2/3 compatibility library); if need support both python 2 , 3, 6 better answer, wanted example free of dependencies on non-bundled modules why did way.
from ctypes import cdll, c_void_p, c_int32, cast, c_char_p, c_wchar_p sys import version_info xunicode = str if version_info[0] > 2 else eval("unicode") # if running under cygwin python, use dll name # if running under non-cygwin windows python, use full path cygwin1.dll # note python , cygwin1.dll must match bitness (i.e. 32-bit python must # use 32-bit cygwin1.dll, 64-bit python must use 64-bit cygwin1.dll.) cygwin = cdll.loadlibrary("cygwin1.dll") cygwin_create_path = cygwin.cygwin_create_path cygwin_create_path.restype = c_void_p cygwin_create_path.argtypes = [c_int32, c_void_p] # initialise cygwin dll. step should done if using # non-cygwin python. if using cygwin python don't because # has been done you. cygwin_dll_init = cygwin.cygwin_dll_init cygwin_dll_init.restype = none cygwin_dll_init.argtypes = [] cygwin_dll_init() free = cygwin.free free.restype = none free.argtypes = [c_void_p] ccp_posix_to_win_a = 0 ccp_posix_to_win_w = 1 ccp_win_a_to_posix = 2 ccp_win_w_to_posix = 3 def win2posix(path): """convert windows path cygwin path""" result = cygwin_create_path(ccp_win_w_to_posix,xunicode(path)) if result none: raise exception("cygwin_create_path failed") value = cast(result,c_char_p).value free(result) return value def posix2win(path): """convert cygwin path windows path""" result = cygwin_create_path(ccp_posix_to_win_w,str(path)) if result none: raise exception("cygwin_create_path failed") value = cast(result,c_wchar_p).value free(result) return value # example, convert localappdata cygwin path , os import environ localappdata = environ["localappdata"] print("original win32 path: %s" % localappdata) localappdata = win2posix(localappdata) print("as posix path: %s" % localappdata) localappdata = posix2win(localappdata) print("back windows path: %s" % localappdata)
Comments
Post a Comment