È possibile utilizzare ctypes
. Secondo the documentation on MSDN, GetShortPathName
è in KERNEL32.DLL
. Si noti che le funzioni reali sono GetShortPathNameW
per w ide (Unicode) caratteri e GetShortPathNameA
per caratteri a byte singolo. Dal momento che i caratteri ampi sono più generali, useremo quella versione. In primo luogo, impostare il prototipo in base alla documentazione:
import ctypes
from ctypes import wintypes
_GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW
_GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]
_GetShortPathNameW.restype = wintypes.DWORD
GetShortPathName
è utilizzato da prima chiamando senza un buffer di destinazione. Restituirà il numero di caratteri necessario per creare il buffer di destinazione. Quindi lo chiami di nuovo con un buffer di quella dimensione. Se, a causa di un problema di TOCTTOU, il valore restituito è ancora più grande, continua a provare finché non lo ottieni correttamente. Quindi:
def get_short_path_name(long_name):
"""
Gets the short path name of a given long path.
http://stackoverflow.com/a/23598461/200291
"""
output_buf_size = 0
while True:
output_buf = ctypes.create_unicode_buffer(output_buf_size)
needed = _GetShortPathNameW(long_name, output_buf, output_buf_size)
if output_buf_size >= needed:
return output_buf.value
else:
output_buf_size = needed
@ruslo: Oops, hai ragione! Grazie. – icktoofay
Ciao, il pezzo di codice sembra essere perfetto per me, tranne quando aggiungo l'ultima cartella. Avresti un'idea sul perché? Ecco il percorso 'C: \ data \ SIEA \ _0 Mise à niveau des boites \ Zona NRA de Ferney \ Ornex 04-05 \ APD_e \ 06_Indirizzo finanziario - IPE' –