Python Library Media
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

__init__.py 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. media (Media Tools)
  6. ===================
  7. **Author:**
  8. * Dirk Alders <sudo-dirk@mount-mockery.de>
  9. **Description:**
  10. This module helps on all issues with media files, like tags (e.g. exif, id3) and transformations.
  11. **Submodules:**
  12. * :mod:`mmod.module.sub1`
  13. * :class:`mmod.module.sub2`
  14. * :func:`mmod.module.sub2`
  15. **Unittest:**
  16. See also the :download:`unittest <../../media/_testresults_/unittest.pdf>` documentation.
  17. """
  18. __DEPENDENCIES__ = []
  19. import logging
  20. logger_name = 'FSTOOLS'
  21. logger = logging.getLogger(logger_name)
  22. __DESCRIPTION__ = """The Module {\\tt %s} is designed to help on all issues with media files, like tags (e.g. exif, id3) and transformations.
  23. For more Information read the documentation.""" % __name__.replace('_', '\_')
  24. """The Module Description"""
  25. __INTERPRETER__ = (2, 3)
  26. """The Tested Interpreter-Versions"""
  27. def uid(pathname, max_staleness=3600):
  28. """
  29. Function returning a unique id for a given file or path.
  30. :param str pathname: File or Path name for generation of the uid.
  31. :param int max_staleness: If a file or path is older than that, we may consider
  32. it stale and return a different uid - this is a
  33. dirty trick to work around changes never being
  34. detected. Default is 3600 seconds, use None to
  35. disable this trickery. See below for more details.
  36. :returns: An object that changes value if the file changed,
  37. None is returned if there were problems accessing the file
  38. :rtype: str
  39. .. note:: Depending on the operating system capabilities and the way the
  40. file update is done, this function might return the same value
  41. even if the file has changed. It should be better than just
  42. using file's mtime though.
  43. max_staleness tries to avoid the worst for these cases.
  44. .. note:: If this function is used for a path, it will stat all pathes and files rekursively.
  45. Using just the file's mtime to determine if the file has changed is
  46. not reliable - if file updates happen faster than the file system's
  47. mtime granularity, then the modification is not detectable because
  48. the mtime is still the same.
  49. This function tries to improve by using not only the mtime, but also
  50. other metadata values like file size and inode to improve reliability.
  51. For the calculation of this value, we of course only want to use data
  52. that we can get rather fast, thus we use file metadata, not file data
  53. (file content).
  54. >>> print 'UID:', uid(__file__)
  55. UID: 16a65cc78e1344e596ef1c9536dab2193a402934
  56. """
  57. if os.path.isdir(pathname):
  58. pathlist = dirlist(pathname) + filelist(pathname)
  59. pathlist.sort()
  60. else:
  61. pathlist = [pathname]
  62. uid = []
  63. for element in pathlist:
  64. try:
  65. st = os.stat(element)
  66. except (IOError, OSError):
  67. uid.append(None) # for permanent errors on stat() this does not change, but
  68. # having a changing value would be pointless because if we
  69. # can't even stat the file, it is unlikely we can read it.
  70. else:
  71. fake_mtime = int(st.st_mtime)
  72. if not st.st_ino and max_staleness:
  73. # st_ino being 0 likely means that we run on a platform not
  74. # supporting it (e.g. win32) - thus we likely need this dirty
  75. # trick
  76. now = int(time.time())
  77. if now >= st.st_mtime + max_staleness:
  78. # keep same fake_mtime for each max_staleness interval
  79. fake_mtime = int(now / max_staleness) * max_staleness
  80. uid.append((
  81. st.st_mtime, # might have a rather rough granularity, e.g. 2s
  82. # on FAT, 1s on ext3 and might not change on fast
  83. # updates
  84. st.st_ino, # inode number (will change if the update is done
  85. # by e.g. renaming a temp file to the real file).
  86. # not supported on win32 (0 ever)
  87. st.st_size, # likely to change on many updates, but not
  88. # sufficient alone
  89. fake_mtime) # trick to workaround file system / platform
  90. # limitations causing permanent trouble
  91. )
  92. if sys.version_info < (3, 0):
  93. secret = ''
  94. return hmac.new(secret, repr(uid), hashlib.sha1).hexdigest()
  95. else:
  96. secret = b''
  97. return hmac.new(secret, bytes(repr(uid), 'latin-1'), hashlib.sha1).hexdigest()
  98. def uid_filelist(path='.', expression='*', rekursive=True):
  99. SHAhash = hashlib.md5()
  100. #
  101. fl = filelist(path, expression, rekursive)
  102. fl.sort()
  103. for f in fl:
  104. if sys.version_info < (3, 0):
  105. with open(f, 'rb') as fh:
  106. SHAhash.update(hashlib.md5(fh.read()).hexdigest())
  107. else:
  108. with open(f, mode='rb') as fh:
  109. d = hashlib.md5()
  110. for buf in iter(partial(fh.read, 128), b''):
  111. d.update(buf)
  112. SHAhash.update(d.hexdigest().encode())
  113. #
  114. return SHAhash.hexdigest()
  115. def filelist(path='.', expression='*', rekursive=True):
  116. """
  117. Function returning a list of files below a given path.
  118. :param str path: folder which is the basepath for searching files.
  119. :param str expression: expression to fit including shell-style wildcards.
  120. :param bool rekursive: search all subfolders if True.
  121. :returns: list of filenames including the pathe
  122. :rtype: list
  123. .. note:: The returned filenames could be relative pathes depending on argument path.
  124. >>> for filename in filelist(path='.', expression='*.py*', rekursive=True):
  125. ... print filename
  126. ./__init__.py
  127. ./__init__.pyc
  128. """
  129. li = list()
  130. if os.path.exists(path):
  131. logger.debug('FILELIST: path (%s) exists - looking for files to append', path)
  132. for filename in glob.glob(os.path.join(path, expression)):
  133. if os.path.isfile(filename):
  134. li.append(filename)
  135. for directory in os.listdir(path):
  136. directory = os.path.join(path, directory)
  137. if os.path.isdir(directory) and rekursive and not os.path.islink(directory):
  138. li.extend(filelist(directory, expression))
  139. else:
  140. logger.warning('FILELIST: path (%s) does not exist - empty filelist will be returned', path)
  141. return li
  142. def dirlist(path='.', rekursive=True):
  143. """
  144. Function returning a list of directories below a given path.
  145. :param str path: folder which is the basepath for searching files.
  146. :param bool rekursive: search all subfolders if True.
  147. :returns: list of filenames including the pathe
  148. :rtype: list
  149. .. note:: The returned filenames could be relative pathes depending on argument path.
  150. >>> for dirname in dirlist(path='..', rekursive=True):
  151. ... print dirname
  152. ../caching
  153. ../fstools
  154. """
  155. li = list()
  156. if os.path.exists(path):
  157. logger.debug('DIRLIST: path (%s) exists - looking for directories to append', path)
  158. for dirname in os.listdir(path):
  159. fulldir = os.path.join(path, dirname)
  160. if os.path.isdir(fulldir):
  161. li.append(fulldir)
  162. if rekursive:
  163. li.extend(dirlist(fulldir))
  164. else:
  165. logger.warning('DIRLIST: path (%s) does not exist - empty filelist will be returned', path)
  166. return li
  167. def is_writeable(path):
  168. """.. warning:: Needs to be documented
  169. """
  170. if os.access(path, os.W_OK):
  171. # path is writable whatever it is, file or directory
  172. return True
  173. else:
  174. # path is not writable whatever it is, file or directory
  175. return False
  176. def mkdir(path):
  177. """.. warning:: Needs to be documented
  178. """
  179. path = os.path.abspath(path)
  180. if not os.path.exists(os.path.dirname(path)):
  181. mkdir(os.path.dirname(path))
  182. if not os.path.exists(path):
  183. os.mkdir(path)
  184. return os.path.isdir(path)
  185. def open_locked_non_blocking(*args, **kwargs):
  186. """.. warning:: Needs to be documented (acquire exclusive lock file access). Throws an exception, if file is locked!
  187. """
  188. import fcntl
  189. locked_file_descriptor = open(*args, **kwargs)
  190. fcntl.lockf(locked_file_descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
  191. return locked_file_descriptor
  192. def open_locked_blocking(*args, **kwargs):
  193. """.. warning:: Needs to be documented (acquire exclusive lock file access). Blocks until file is free. deadlock!
  194. """
  195. import fcntl
  196. locked_file_descriptor = open(*args, **kwargs)
  197. fcntl.lockf(locked_file_descriptor, fcntl.LOCK_EX)
  198. return locked_file_descriptor