posixfile.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. """Extended file operations available in POSIX.
  2. f = posixfile.open(filename, [mode, [bufsize]])
  3. will create a new posixfile object
  4. f = posixfile.fileopen(fileobject)
  5. will create a posixfile object from a builtin file object
  6. f.file()
  7. will return the original builtin file object
  8. f.dup()
  9. will return a new file object based on a new filedescriptor
  10. f.dup2(fd)
  11. will return a new file object based on the given filedescriptor
  12. f.flags(mode)
  13. will turn on the associated flag (merge)
  14. mode can contain the following characters:
  15. (character representing a flag)
  16. a append only flag
  17. c close on exec flag
  18. n no delay flag
  19. s synchronization flag
  20. (modifiers)
  21. ! turn flags 'off' instead of default 'on'
  22. = copy flags 'as is' instead of default 'merge'
  23. ? return a string in which the characters represent the flags
  24. that are set
  25. note: - the '!' and '=' modifiers are mutually exclusive.
  26. - the '?' modifier will return the status of the flags after they
  27. have been changed by other characters in the mode string
  28. f.lock(mode [, len [, start [, whence]]])
  29. will (un)lock a region
  30. mode can contain the following characters:
  31. (character representing type of lock)
  32. u unlock
  33. r read lock
  34. w write lock
  35. (modifiers)
  36. | wait until the lock can be granted
  37. ? return the first lock conflicting with the requested lock
  38. or 'None' if there is no conflict. The lock returned is in the
  39. format (mode, len, start, whence, pid) where mode is a
  40. character representing the type of lock ('r' or 'w')
  41. note: - the '?' modifier prevents a region from being locked; it is
  42. query only
  43. """
  44. import warnings
  45. warnings.warn(
  46. "The posixfile module is obsolete and will disappear in the future",
  47. DeprecationWarning)
  48. del warnings
  49. class _posixfile_:
  50. """File wrapper class that provides extra POSIX file routines."""
  51. states = ['open', 'closed']
  52. #
  53. # Internal routines
  54. #
  55. def __repr__(self):
  56. file = self._file_
  57. return "<%s posixfile '%s', mode '%s' at %s>" % \
  58. (self.states[file.closed], file.name, file.mode, \
  59. hex(id(self))[2:])
  60. #
  61. # Initialization routines
  62. #
  63. def open(self, name, mode='r', bufsize=-1):
  64. import __builtin__
  65. return self.fileopen(__builtin__.open(name, mode, bufsize))
  66. def fileopen(self, file):
  67. import types
  68. if repr(type(file)) != "<type 'file'>":
  69. raise TypeError, 'posixfile.fileopen() arg must be file object'
  70. self._file_ = file
  71. # Copy basic file methods
  72. for maybemethod in dir(file):
  73. if not maybemethod.startswith('_'):
  74. attr = getattr(file, maybemethod)
  75. if isinstance(attr, types.BuiltinMethodType):
  76. setattr(self, maybemethod, attr)
  77. return self
  78. #
  79. # New methods
  80. #
  81. def file(self):
  82. return self._file_
  83. def dup(self):
  84. import posix
  85. if not hasattr(posix, 'fdopen'):
  86. raise AttributeError, 'dup() method unavailable'
  87. return posix.fdopen(posix.dup(self._file_.fileno()), self._file_.mode)
  88. def dup2(self, fd):
  89. import posix
  90. if not hasattr(posix, 'fdopen'):
  91. raise AttributeError, 'dup() method unavailable'
  92. posix.dup2(self._file_.fileno(), fd)
  93. return posix.fdopen(fd, self._file_.mode)
  94. def flags(self, *which):
  95. import fcntl, os
  96. if which:
  97. if len(which) > 1:
  98. raise TypeError, 'Too many arguments'
  99. which = which[0]
  100. else: which = '?'
  101. l_flags = 0
  102. if 'n' in which: l_flags = l_flags | os.O_NDELAY
  103. if 'a' in which: l_flags = l_flags | os.O_APPEND
  104. if 's' in which: l_flags = l_flags | os.O_SYNC
  105. file = self._file_
  106. if '=' not in which:
  107. cur_fl = fcntl.fcntl(file.fileno(), fcntl.F_GETFL, 0)
  108. if '!' in which: l_flags = cur_fl & ~ l_flags
  109. else: l_flags = cur_fl | l_flags
  110. l_flags = fcntl.fcntl(file.fileno(), fcntl.F_SETFL, l_flags)
  111. if 'c' in which:
  112. arg = ('!' not in which) # 0 is don't, 1 is do close on exec
  113. l_flags = fcntl.fcntl(file.fileno(), fcntl.F_SETFD, arg)
  114. if '?' in which:
  115. which = '' # Return current flags
  116. l_flags = fcntl.fcntl(file.fileno(), fcntl.F_GETFL, 0)
  117. if os.O_APPEND & l_flags: which = which + 'a'
  118. if fcntl.fcntl(file.fileno(), fcntl.F_GETFD, 0) & 1:
  119. which = which + 'c'
  120. if os.O_NDELAY & l_flags: which = which + 'n'
  121. if os.O_SYNC & l_flags: which = which + 's'
  122. return which
  123. def lock(self, how, *args):
  124. import struct, fcntl
  125. if 'w' in how: l_type = fcntl.F_WRLCK
  126. elif 'r' in how: l_type = fcntl.F_RDLCK
  127. elif 'u' in how: l_type = fcntl.F_UNLCK
  128. else: raise TypeError, 'no type of lock specified'
  129. if '|' in how: cmd = fcntl.F_SETLKW
  130. elif '?' in how: cmd = fcntl.F_GETLK
  131. else: cmd = fcntl.F_SETLK
  132. l_whence = 0
  133. l_start = 0
  134. l_len = 0
  135. if len(args) == 1:
  136. l_len = args[0]
  137. elif len(args) == 2:
  138. l_len, l_start = args
  139. elif len(args) == 3:
  140. l_len, l_start, l_whence = args
  141. elif len(args) > 3:
  142. raise TypeError, 'too many arguments'
  143. # Hack by [email protected] to get locking to go on freebsd;
  144. # additions for AIX by [email protected]
  145. import sys, os
  146. if sys.platform in ('netbsd1',
  147. 'openbsd2',
  148. 'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5',
  149. 'freebsd6', 'bsdos2', 'bsdos3', 'bsdos4'):
  150. flock = struct.pack('lxxxxlxxxxlhh', \
  151. l_start, l_len, os.getpid(), l_type, l_whence)
  152. elif sys.platform in ['aix3', 'aix4']:
  153. flock = struct.pack('hhlllii', \
  154. l_type, l_whence, l_start, l_len, 0, 0, 0)
  155. else:
  156. flock = struct.pack('hhllhh', \
  157. l_type, l_whence, l_start, l_len, 0, 0)
  158. flock = fcntl.fcntl(self._file_.fileno(), cmd, flock)
  159. if '?' in how:
  160. if sys.platform in ('netbsd1',
  161. 'openbsd2',
  162. 'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5',
  163. 'bsdos2', 'bsdos3', 'bsdos4'):
  164. l_start, l_len, l_pid, l_type, l_whence = \
  165. struct.unpack('lxxxxlxxxxlhh', flock)
  166. elif sys.platform in ['aix3', 'aix4']:
  167. l_type, l_whence, l_start, l_len, l_sysid, l_pid, l_vfs = \
  168. struct.unpack('hhlllii', flock)
  169. elif sys.platform == "linux2":
  170. l_type, l_whence, l_start, l_len, l_pid, l_sysid = \
  171. struct.unpack('hhllhh', flock)
  172. else:
  173. l_type, l_whence, l_start, l_len, l_sysid, l_pid = \
  174. struct.unpack('hhllhh', flock)
  175. if l_type != fcntl.F_UNLCK:
  176. if l_type == fcntl.F_RDLCK:
  177. return 'r', l_len, l_start, l_whence, l_pid
  178. else:
  179. return 'w', l_len, l_start, l_whence, l_pid
  180. def open(name, mode='r', bufsize=-1):
  181. """Public routine to open a file as a posixfile object."""
  182. return _posixfile_().open(name, mode, bufsize)
  183. def fileopen(file):
  184. """Public routine to get a posixfile object from a Python file object."""
  185. return _posixfile_().fileopen(file)
  186. #
  187. # Constants
  188. #
  189. SEEK_SET = 0
  190. SEEK_CUR = 1
  191. SEEK_END = 2
  192. #
  193. # End of posixfile.py
  194. #