Resolving firmlinks in Python
I recently had the need to resolve firmlinks in python. For example given a path like /Applications/Safari.app
, I needed to get /System/Volumes/Data/Applications/Safari.app
.
Turns out there is not a single example of this anywhere online, so if you are in the same place as I am, here is an example of how to do that:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fcntl | |
import os | |
path = '/Applications/Safari.app/' | |
# MacOS-only fcntl command defined in xnu/bsd/sys/fcntl.h | |
F_GETPATH_NOFIRMLINK = 102 | |
# The documented max length of an fcntl buffer in python documentation. | |
FCNTL_MAX_LENGTH = 1024 | |
fd = os.open(path, os.O_DIRECTORY) | |
full_path_bytes = fcntl.fcntl(fd, F_GETPATH_NOFIRMLINK, bytes(FCNTL_MAX_LENGTH)) | |
full_path = full_path_bytes.decode('utf-8') |