1
0

loader.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from ctypes.util import find_library
  2. import ctypes
  3. import sys
  4. import glob
  5. import os.path
  6. def _lib_candidates():
  7. yield find_library('magic')
  8. if sys.platform == 'darwin':
  9. paths = [
  10. '/opt/local/lib',
  11. '/usr/local/lib',
  12. '/opt/homebrew/lib',
  13. ] + glob.glob('/usr/local/Cellar/libmagic/*/lib')
  14. for i in paths:
  15. yield os.path.join(i, 'libmagic.dylib')
  16. elif sys.platform in ('win32', 'cygwin'):
  17. prefixes = ['libmagic', 'magic1', 'cygmagic-1', 'libmagic-1', 'msys-magic-1']
  18. for i in prefixes:
  19. # find_library searches in %PATH% but not the current directory,
  20. # so look for both
  21. yield './%s.dll' % (i,)
  22. yield find_library(i)
  23. elif sys.platform == 'linux':
  24. # This is necessary because alpine is bad
  25. yield 'libmagic.so.1'
  26. def load_lib():
  27. for lib in _lib_candidates():
  28. # find_library returns None when lib not found
  29. if lib is None:
  30. continue
  31. try:
  32. return ctypes.CDLL(lib)
  33. except OSError:
  34. pass
  35. else:
  36. # It is better to raise an ImportError since we are importing magic module
  37. raise ImportError('failed to find libmagic. Check your installation')