_pyio.py 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530
  1. """
  2. Python implementation of the io module.
  3. """
  4. import os
  5. import abc
  6. import codecs
  7. import errno
  8. import array
  9. import stat
  10. import sys
  11. # Import _thread instead of threading to reduce startup cost
  12. try:
  13. from _thread import allocate_lock as Lock
  14. except ImportError:
  15. from _dummy_thread import allocate_lock as Lock
  16. if sys.platform in {'win32', 'cygwin'}:
  17. from msvcrt import setmode as _setmode
  18. else:
  19. _setmode = None
  20. import io
  21. from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
  22. valid_seek_flags = {0, 1, 2} # Hardwired values
  23. if hasattr(os, 'SEEK_HOLE') :
  24. valid_seek_flags.add(os.SEEK_HOLE)
  25. valid_seek_flags.add(os.SEEK_DATA)
  26. # open() uses st_blksize whenever we can
  27. DEFAULT_BUFFER_SIZE = 8 * 1024 # bytes
  28. # NOTE: Base classes defined here are registered with the "official" ABCs
  29. # defined in io.py. We don't use real inheritance though, because we don't want
  30. # to inherit the C implementations.
  31. # Rebind for compatibility
  32. BlockingIOError = BlockingIOError
  33. def open(file, mode="r", buffering=-1, encoding=None, errors=None,
  34. newline=None, closefd=True, opener=None):
  35. r"""Open file and return a stream. Raise OSError upon failure.
  36. file is either a text or byte string giving the name (and the path
  37. if the file isn't in the current working directory) of the file to
  38. be opened or an integer file descriptor of the file to be
  39. wrapped. (If a file descriptor is given, it is closed when the
  40. returned I/O object is closed, unless closefd is set to False.)
  41. mode is an optional string that specifies the mode in which the file is
  42. opened. It defaults to 'r' which means open for reading in text mode. Other
  43. common values are 'w' for writing (truncating the file if it already
  44. exists), 'x' for exclusive creation of a new file, and 'a' for appending
  45. (which on some Unix systems, means that all writes append to the end of the
  46. file regardless of the current seek position). In text mode, if encoding is
  47. not specified the encoding used is platform dependent. (For reading and
  48. writing raw bytes use binary mode and leave encoding unspecified.) The
  49. available modes are:
  50. ========= ===============================================================
  51. Character Meaning
  52. --------- ---------------------------------------------------------------
  53. 'r' open for reading (default)
  54. 'w' open for writing, truncating the file first
  55. 'x' create a new file and open it for writing
  56. 'a' open for writing, appending to the end of the file if it exists
  57. 'b' binary mode
  58. 't' text mode (default)
  59. '+' open a disk file for updating (reading and writing)
  60. 'U' universal newline mode (deprecated)
  61. ========= ===============================================================
  62. The default mode is 'rt' (open for reading text). For binary random
  63. access, the mode 'w+b' opens and truncates the file to 0 bytes, while
  64. 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
  65. raises an `FileExistsError` if the file already exists.
  66. Python distinguishes between files opened in binary and text modes,
  67. even when the underlying operating system doesn't. Files opened in
  68. binary mode (appending 'b' to the mode argument) return contents as
  69. bytes objects without any decoding. In text mode (the default, or when
  70. 't' is appended to the mode argument), the contents of the file are
  71. returned as strings, the bytes having been first decoded using a
  72. platform-dependent encoding or using the specified encoding if given.
  73. 'U' mode is deprecated and will raise an exception in future versions
  74. of Python. It has no effect in Python 3. Use newline to control
  75. universal newlines mode.
  76. buffering is an optional integer used to set the buffering policy.
  77. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
  78. line buffering (only usable in text mode), and an integer > 1 to indicate
  79. the size of a fixed-size chunk buffer. When no buffering argument is
  80. given, the default buffering policy works as follows:
  81. * Binary files are buffered in fixed-size chunks; the size of the buffer
  82. is chosen using a heuristic trying to determine the underlying device's
  83. "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
  84. On many systems, the buffer will typically be 4096 or 8192 bytes long.
  85. * "Interactive" text files (files for which isatty() returns True)
  86. use line buffering. Other text files use the policy described above
  87. for binary files.
  88. encoding is the str name of the encoding used to decode or encode the
  89. file. This should only be used in text mode. The default encoding is
  90. platform dependent, but any encoding supported by Python can be
  91. passed. See the codecs module for the list of supported encodings.
  92. errors is an optional string that specifies how encoding errors are to
  93. be handled---this argument should not be used in binary mode. Pass
  94. 'strict' to raise a ValueError exception if there is an encoding error
  95. (the default of None has the same effect), or pass 'ignore' to ignore
  96. errors. (Note that ignoring encoding errors can lead to data loss.)
  97. See the documentation for codecs.register for a list of the permitted
  98. encoding error strings.
  99. newline is a string controlling how universal newlines works (it only
  100. applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works
  101. as follows:
  102. * On input, if newline is None, universal newlines mode is
  103. enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
  104. these are translated into '\n' before being returned to the
  105. caller. If it is '', universal newline mode is enabled, but line
  106. endings are returned to the caller untranslated. If it has any of
  107. the other legal values, input lines are only terminated by the given
  108. string, and the line ending is returned to the caller untranslated.
  109. * On output, if newline is None, any '\n' characters written are
  110. translated to the system default line separator, os.linesep. If
  111. newline is '', no translation takes place. If newline is any of the
  112. other legal values, any '\n' characters written are translated to
  113. the given string.
  114. closedfd is a bool. If closefd is False, the underlying file descriptor will
  115. be kept open when the file is closed. This does not work when a file name is
  116. given and must be True in that case.
  117. The newly created file is non-inheritable.
  118. A custom opener can be used by passing a callable as *opener*. The
  119. underlying file descriptor for the file object is then obtained by calling
  120. *opener* with (*file*, *flags*). *opener* must return an open file
  121. descriptor (passing os.open as *opener* results in functionality similar to
  122. passing None).
  123. open() returns a file object whose type depends on the mode, and
  124. through which the standard file operations such as reading and writing
  125. are performed. When open() is used to open a file in a text mode ('w',
  126. 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
  127. a file in a binary mode, the returned class varies: in read binary
  128. mode, it returns a BufferedReader; in write binary and append binary
  129. modes, it returns a BufferedWriter, and in read/write mode, it returns
  130. a BufferedRandom.
  131. It is also possible to use a string or bytearray as a file for both
  132. reading and writing. For strings StringIO can be used like a file
  133. opened in a text mode, and for bytes a BytesIO can be used like a file
  134. opened in a binary mode.
  135. """
  136. if not isinstance(file, (str, bytes, int)):
  137. raise TypeError("invalid file: %r" % file)
  138. if not isinstance(mode, str):
  139. raise TypeError("invalid mode: %r" % mode)
  140. if not isinstance(buffering, int):
  141. raise TypeError("invalid buffering: %r" % buffering)
  142. if encoding is not None and not isinstance(encoding, str):
  143. raise TypeError("invalid encoding: %r" % encoding)
  144. if errors is not None and not isinstance(errors, str):
  145. raise TypeError("invalid errors: %r" % errors)
  146. modes = set(mode)
  147. if modes - set("axrwb+tU") or len(mode) > len(modes):
  148. raise ValueError("invalid mode: %r" % mode)
  149. creating = "x" in modes
  150. reading = "r" in modes
  151. writing = "w" in modes
  152. appending = "a" in modes
  153. updating = "+" in modes
  154. text = "t" in modes
  155. binary = "b" in modes
  156. if "U" in modes:
  157. if creating or writing or appending:
  158. raise ValueError("can't use U and writing mode at once")
  159. import warnings
  160. warnings.warn("'U' mode is deprecated",
  161. DeprecationWarning, 2)
  162. reading = True
  163. if text and binary:
  164. raise ValueError("can't have text and binary mode at once")
  165. if creating + reading + writing + appending > 1:
  166. raise ValueError("can't have read/write/append mode at once")
  167. if not (creating or reading or writing or appending):
  168. raise ValueError("must have exactly one of read/write/append mode")
  169. if binary and encoding is not None:
  170. raise ValueError("binary mode doesn't take an encoding argument")
  171. if binary and errors is not None:
  172. raise ValueError("binary mode doesn't take an errors argument")
  173. if binary and newline is not None:
  174. raise ValueError("binary mode doesn't take a newline argument")
  175. raw = FileIO(file,
  176. (creating and "x" or "") +
  177. (reading and "r" or "") +
  178. (writing and "w" or "") +
  179. (appending and "a" or "") +
  180. (updating and "+" or ""),
  181. closefd, opener=opener)
  182. result = raw
  183. try:
  184. line_buffering = False
  185. if buffering == 1 or buffering < 0 and raw.isatty():
  186. buffering = -1
  187. line_buffering = True
  188. if buffering < 0:
  189. buffering = DEFAULT_BUFFER_SIZE
  190. try:
  191. bs = os.fstat(raw.fileno()).st_blksize
  192. except (OSError, AttributeError):
  193. pass
  194. else:
  195. if bs > 1:
  196. buffering = bs
  197. if buffering < 0:
  198. raise ValueError("invalid buffering size")
  199. if buffering == 0:
  200. if binary:
  201. return result
  202. raise ValueError("can't have unbuffered text I/O")
  203. if updating:
  204. buffer = BufferedRandom(raw, buffering)
  205. elif creating or writing or appending:
  206. buffer = BufferedWriter(raw, buffering)
  207. elif reading:
  208. buffer = BufferedReader(raw, buffering)
  209. else:
  210. raise ValueError("unknown mode: %r" % mode)
  211. result = buffer
  212. if binary:
  213. return result
  214. text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
  215. result = text
  216. text.mode = mode
  217. return result
  218. except:
  219. result.close()
  220. raise
  221. class DocDescriptor:
  222. """Helper for builtins.open.__doc__
  223. """
  224. def __get__(self, obj, typ):
  225. return (
  226. "open(file, mode='r', buffering=-1, encoding=None, "
  227. "errors=None, newline=None, closefd=True)\n\n" +
  228. open.__doc__)
  229. class OpenWrapper:
  230. """Wrapper for builtins.open
  231. Trick so that open won't become a bound method when stored
  232. as a class variable (as dbm.dumb does).
  233. See initstdio() in Python/pylifecycle.c.
  234. """
  235. __doc__ = DocDescriptor()
  236. def __new__(cls, *args, **kwargs):
  237. return open(*args, **kwargs)
  238. # In normal operation, both `UnsupportedOperation`s should be bound to the
  239. # same object.
  240. try:
  241. UnsupportedOperation = io.UnsupportedOperation
  242. except AttributeError:
  243. class UnsupportedOperation(ValueError, OSError):
  244. pass
  245. class IOBase(metaclass=abc.ABCMeta):
  246. """The abstract base class for all I/O classes, acting on streams of
  247. bytes. There is no public constructor.
  248. This class provides dummy implementations for many methods that
  249. derived classes can override selectively; the default implementations
  250. represent a file that cannot be read, written or seeked.
  251. Even though IOBase does not declare read, readinto, or write because
  252. their signatures will vary, implementations and clients should
  253. consider those methods part of the interface. Also, implementations
  254. may raise UnsupportedOperation when operations they do not support are
  255. called.
  256. The basic type used for binary data read from or written to a file is
  257. bytes. Other bytes-like objects are accepted as method arguments too. In
  258. some cases (such as readinto), a writable object is required. Text I/O
  259. classes work with str data.
  260. Note that calling any method (even inquiries) on a closed stream is
  261. undefined. Implementations may raise OSError in this case.
  262. IOBase (and its subclasses) support the iterator protocol, meaning
  263. that an IOBase object can be iterated over yielding the lines in a
  264. stream.
  265. IOBase also supports the :keyword:`with` statement. In this example,
  266. fp is closed after the suite of the with statement is complete:
  267. with open('spam.txt', 'r') as fp:
  268. fp.write('Spam and eggs!')
  269. """
  270. ### Internal ###
  271. def _unsupported(self, name):
  272. """Internal: raise an OSError exception for unsupported operations."""
  273. raise UnsupportedOperation("%s.%s() not supported" %
  274. (self.__class__.__name__, name))
  275. ### Positioning ###
  276. def seek(self, pos, whence=0):
  277. """Change stream position.
  278. Change the stream position to byte offset pos. Argument pos is
  279. interpreted relative to the position indicated by whence. Values
  280. for whence are ints:
  281. * 0 -- start of stream (the default); offset should be zero or positive
  282. * 1 -- current stream position; offset may be negative
  283. * 2 -- end of stream; offset is usually negative
  284. Some operating systems / file systems could provide additional values.
  285. Return an int indicating the new absolute position.
  286. """
  287. self._unsupported("seek")
  288. def tell(self):
  289. """Return an int indicating the current stream position."""
  290. return self.seek(0, 1)
  291. def truncate(self, pos=None):
  292. """Truncate file to size bytes.
  293. Size defaults to the current IO position as reported by tell(). Return
  294. the new size.
  295. """
  296. self._unsupported("truncate")
  297. ### Flush and close ###
  298. def flush(self):
  299. """Flush write buffers, if applicable.
  300. This is not implemented for read-only and non-blocking streams.
  301. """
  302. self._checkClosed()
  303. # XXX Should this return the number of bytes written???
  304. __closed = False
  305. def close(self):
  306. """Flush and close the IO object.
  307. This method has no effect if the file is already closed.
  308. """
  309. if not self.__closed:
  310. try:
  311. self.flush()
  312. finally:
  313. self.__closed = True
  314. def __del__(self):
  315. """Destructor. Calls close()."""
  316. # The try/except block is in case this is called at program
  317. # exit time, when it's possible that globals have already been
  318. # deleted, and then the close() call might fail. Since
  319. # there's nothing we can do about such failures and they annoy
  320. # the end users, we suppress the traceback.
  321. try:
  322. self.close()
  323. except:
  324. pass
  325. ### Inquiries ###
  326. def seekable(self):
  327. """Return a bool indicating whether object supports random access.
  328. If False, seek(), tell() and truncate() will raise OSError.
  329. This method may need to do a test seek().
  330. """
  331. return False
  332. def _checkSeekable(self, msg=None):
  333. """Internal: raise UnsupportedOperation if file is not seekable
  334. """
  335. if not self.seekable():
  336. raise UnsupportedOperation("File or stream is not seekable."
  337. if msg is None else msg)
  338. def readable(self):
  339. """Return a bool indicating whether object was opened for reading.
  340. If False, read() will raise OSError.
  341. """
  342. return False
  343. def _checkReadable(self, msg=None):
  344. """Internal: raise UnsupportedOperation if file is not readable
  345. """
  346. if not self.readable():
  347. raise UnsupportedOperation("File or stream is not readable."
  348. if msg is None else msg)
  349. def writable(self):
  350. """Return a bool indicating whether object was opened for writing.
  351. If False, write() and truncate() will raise OSError.
  352. """
  353. return False
  354. def _checkWritable(self, msg=None):
  355. """Internal: raise UnsupportedOperation if file is not writable
  356. """
  357. if not self.writable():
  358. raise UnsupportedOperation("File or stream is not writable."
  359. if msg is None else msg)
  360. @property
  361. def closed(self):
  362. """closed: bool. True iff the file has been closed.
  363. For backwards compatibility, this is a property, not a predicate.
  364. """
  365. return self.__closed
  366. def _checkClosed(self, msg=None):
  367. """Internal: raise a ValueError if file is closed
  368. """
  369. if self.closed:
  370. raise ValueError("I/O operation on closed file."
  371. if msg is None else msg)
  372. ### Context manager ###
  373. def __enter__(self): # That's a forward reference
  374. """Context management protocol. Returns self (an instance of IOBase)."""
  375. self._checkClosed()
  376. return self
  377. def __exit__(self, *args):
  378. """Context management protocol. Calls close()"""
  379. self.close()
  380. ### Lower-level APIs ###
  381. # XXX Should these be present even if unimplemented?
  382. def fileno(self):
  383. """Returns underlying file descriptor (an int) if one exists.
  384. An OSError is raised if the IO object does not use a file descriptor.
  385. """
  386. self._unsupported("fileno")
  387. def isatty(self):
  388. """Return a bool indicating whether this is an 'interactive' stream.
  389. Return False if it can't be determined.
  390. """
  391. self._checkClosed()
  392. return False
  393. ### Readline[s] and writelines ###
  394. def readline(self, size=-1):
  395. r"""Read and return a line of bytes from the stream.
  396. If size is specified, at most size bytes will be read.
  397. Size should be an int.
  398. The line terminator is always b'\n' for binary files; for text
  399. files, the newlines argument to open can be used to select the line
  400. terminator(s) recognized.
  401. """
  402. # For backwards compatibility, a (slowish) readline().
  403. if hasattr(self, "peek"):
  404. def nreadahead():
  405. readahead = self.peek(1)
  406. if not readahead:
  407. return 1
  408. n = (readahead.find(b"\n") + 1) or len(readahead)
  409. if size >= 0:
  410. n = min(n, size)
  411. return n
  412. else:
  413. def nreadahead():
  414. return 1
  415. if size is None:
  416. size = -1
  417. elif not isinstance(size, int):
  418. raise TypeError("size must be an integer")
  419. res = bytearray()
  420. while size < 0 or len(res) < size:
  421. b = self.read(nreadahead())
  422. if not b:
  423. break
  424. res += b
  425. if res.endswith(b"\n"):
  426. break
  427. return bytes(res)
  428. def __iter__(self):
  429. self._checkClosed()
  430. return self
  431. def __next__(self):
  432. line = self.readline()
  433. if not line:
  434. raise StopIteration
  435. return line
  436. def readlines(self, hint=None):
  437. """Return a list of lines from the stream.
  438. hint can be specified to control the number of lines read: no more
  439. lines will be read if the total size (in bytes/characters) of all
  440. lines so far exceeds hint.
  441. """
  442. if hint is None or hint <= 0:
  443. return list(self)
  444. n = 0
  445. lines = []
  446. for line in self:
  447. lines.append(line)
  448. n += len(line)
  449. if n >= hint:
  450. break
  451. return lines
  452. def writelines(self, lines):
  453. self._checkClosed()
  454. for line in lines:
  455. self.write(line)
  456. io.IOBase.register(IOBase)
  457. class RawIOBase(IOBase):
  458. """Base class for raw binary I/O."""
  459. # The read() method is implemented by calling readinto(); derived
  460. # classes that want to support read() only need to implement
  461. # readinto() as a primitive operation. In general, readinto() can be
  462. # more efficient than read().
  463. # (It would be tempting to also provide an implementation of
  464. # readinto() in terms of read(), in case the latter is a more suitable
  465. # primitive operation, but that would lead to nasty recursion in case
  466. # a subclass doesn't implement either.)
  467. def read(self, size=-1):
  468. """Read and return up to size bytes, where size is an int.
  469. Returns an empty bytes object on EOF, or None if the object is
  470. set not to block and has no data to read.
  471. """
  472. if size is None:
  473. size = -1
  474. if size < 0:
  475. return self.readall()
  476. b = bytearray(size.__index__())
  477. n = self.readinto(b)
  478. if n is None:
  479. return None
  480. del b[n:]
  481. return bytes(b)
  482. def readall(self):
  483. """Read until EOF, using multiple read() call."""
  484. res = bytearray()
  485. while True:
  486. data = self.read(DEFAULT_BUFFER_SIZE)
  487. if not data:
  488. break
  489. res += data
  490. if res:
  491. return bytes(res)
  492. else:
  493. # b'' or None
  494. return data
  495. def readinto(self, b):
  496. """Read bytes into a pre-allocated bytes-like object b.
  497. Returns an int representing the number of bytes read (0 for EOF), or
  498. None if the object is set not to block and has no data to read.
  499. """
  500. self._unsupported("readinto")
  501. def write(self, b):
  502. """Write the given buffer to the IO stream.
  503. Returns the number of bytes written, which may be less than the
  504. length of b in bytes.
  505. """
  506. self._unsupported("write")
  507. io.RawIOBase.register(RawIOBase)
  508. from _io import FileIO
  509. RawIOBase.register(FileIO)
  510. class BufferedIOBase(IOBase):
  511. """Base class for buffered IO objects.
  512. The main difference with RawIOBase is that the read() method
  513. supports omitting the size argument, and does not have a default
  514. implementation that defers to readinto().
  515. In addition, read(), readinto() and write() may raise
  516. BlockingIOError if the underlying raw stream is in non-blocking
  517. mode and not ready; unlike their raw counterparts, they will never
  518. return None.
  519. A typical implementation should not inherit from a RawIOBase
  520. implementation, but wrap one.
  521. """
  522. def read(self, size=None):
  523. """Read and return up to size bytes, where size is an int.
  524. If the argument is omitted, None, or negative, reads and
  525. returns all data until EOF.
  526. If the argument is positive, and the underlying raw stream is
  527. not 'interactive', multiple raw reads may be issued to satisfy
  528. the byte count (unless EOF is reached first). But for
  529. interactive raw streams (XXX and for pipes?), at most one raw
  530. read will be issued, and a short result does not imply that
  531. EOF is imminent.
  532. Returns an empty bytes array on EOF.
  533. Raises BlockingIOError if the underlying raw stream has no
  534. data at the moment.
  535. """
  536. self._unsupported("read")
  537. def read1(self, size=None):
  538. """Read up to size bytes with at most one read() system call,
  539. where size is an int.
  540. """
  541. self._unsupported("read1")
  542. def readinto(self, b):
  543. """Read bytes into a pre-allocated bytes-like object b.
  544. Like read(), this may issue multiple reads to the underlying raw
  545. stream, unless the latter is 'interactive'.
  546. Returns an int representing the number of bytes read (0 for EOF).
  547. Raises BlockingIOError if the underlying raw stream has no
  548. data at the moment.
  549. """
  550. return self._readinto(b, read1=False)
  551. def readinto1(self, b):
  552. """Read bytes into buffer *b*, using at most one system call
  553. Returns an int representing the number of bytes read (0 for EOF).
  554. Raises BlockingIOError if the underlying raw stream has no
  555. data at the moment.
  556. """
  557. return self._readinto(b, read1=True)
  558. def _readinto(self, b, read1):
  559. if not isinstance(b, memoryview):
  560. b = memoryview(b)
  561. b = b.cast('B')
  562. if read1:
  563. data = self.read1(len(b))
  564. else:
  565. data = self.read(len(b))
  566. n = len(data)
  567. b[:n] = data
  568. return n
  569. def write(self, b):
  570. """Write the given bytes buffer to the IO stream.
  571. Return the number of bytes written, which is always the length of b
  572. in bytes.
  573. Raises BlockingIOError if the buffer is full and the
  574. underlying raw stream cannot accept more data at the moment.
  575. """
  576. self._unsupported("write")
  577. def detach(self):
  578. """
  579. Separate the underlying raw stream from the buffer and return it.
  580. After the raw stream has been detached, the buffer is in an unusable
  581. state.
  582. """
  583. self._unsupported("detach")
  584. io.BufferedIOBase.register(BufferedIOBase)
  585. class _BufferedIOMixin(BufferedIOBase):
  586. """A mixin implementation of BufferedIOBase with an underlying raw stream.
  587. This passes most requests on to the underlying raw stream. It
  588. does *not* provide implementations of read(), readinto() or
  589. write().
  590. """
  591. def __init__(self, raw):
  592. self._raw = raw
  593. ### Positioning ###
  594. def seek(self, pos, whence=0):
  595. new_position = self.raw.seek(pos, whence)
  596. if new_position < 0:
  597. raise OSError("seek() returned an invalid position")
  598. return new_position
  599. def tell(self):
  600. pos = self.raw.tell()
  601. if pos < 0:
  602. raise OSError("tell() returned an invalid position")
  603. return pos
  604. def truncate(self, pos=None):
  605. # Flush the stream. We're mixing buffered I/O with lower-level I/O,
  606. # and a flush may be necessary to synch both views of the current
  607. # file state.
  608. self.flush()
  609. if pos is None:
  610. pos = self.tell()
  611. # XXX: Should seek() be used, instead of passing the position
  612. # XXX directly to truncate?
  613. return self.raw.truncate(pos)
  614. ### Flush and close ###
  615. def flush(self):
  616. if self.closed:
  617. raise ValueError("flush of closed file")
  618. self.raw.flush()
  619. def close(self):
  620. if self.raw is not None and not self.closed:
  621. try:
  622. # may raise BlockingIOError or BrokenPipeError etc
  623. self.flush()
  624. finally:
  625. self.raw.close()
  626. def detach(self):
  627. if self.raw is None:
  628. raise ValueError("raw stream already detached")
  629. self.flush()
  630. raw = self._raw
  631. self._raw = None
  632. return raw
  633. ### Inquiries ###
  634. def seekable(self):
  635. return self.raw.seekable()
  636. @property
  637. def raw(self):
  638. return self._raw
  639. @property
  640. def closed(self):
  641. return self.raw.closed
  642. @property
  643. def name(self):
  644. return self.raw.name
  645. @property
  646. def mode(self):
  647. return self.raw.mode
  648. def __getstate__(self):
  649. raise TypeError("can not serialize a '{0}' object"
  650. .format(self.__class__.__name__))
  651. def __repr__(self):
  652. modname = self.__class__.__module__
  653. clsname = self.__class__.__qualname__
  654. try:
  655. name = self.name
  656. except Exception:
  657. return "<{}.{}>".format(modname, clsname)
  658. else:
  659. return "<{}.{} name={!r}>".format(modname, clsname, name)
  660. ### Lower-level APIs ###
  661. def fileno(self):
  662. return self.raw.fileno()
  663. def isatty(self):
  664. return self.raw.isatty()
  665. class BytesIO(BufferedIOBase):
  666. """Buffered I/O implementation using an in-memory bytes buffer."""
  667. def __init__(self, initial_bytes=None):
  668. buf = bytearray()
  669. if initial_bytes is not None:
  670. buf += initial_bytes
  671. self._buffer = buf
  672. self._pos = 0
  673. def __getstate__(self):
  674. if self.closed:
  675. raise ValueError("__getstate__ on closed file")
  676. return self.__dict__.copy()
  677. def getvalue(self):
  678. """Return the bytes value (contents) of the buffer
  679. """
  680. if self.closed:
  681. raise ValueError("getvalue on closed file")
  682. return bytes(self._buffer)
  683. def getbuffer(self):
  684. """Return a readable and writable view of the buffer.
  685. """
  686. if self.closed:
  687. raise ValueError("getbuffer on closed file")
  688. return memoryview(self._buffer)
  689. def close(self):
  690. self._buffer.clear()
  691. super().close()
  692. def read(self, size=None):
  693. if self.closed:
  694. raise ValueError("read from closed file")
  695. if size is None:
  696. size = -1
  697. if size < 0:
  698. size = len(self._buffer)
  699. if len(self._buffer) <= self._pos:
  700. return b""
  701. newpos = min(len(self._buffer), self._pos + size)
  702. b = self._buffer[self._pos : newpos]
  703. self._pos = newpos
  704. return bytes(b)
  705. def read1(self, size):
  706. """This is the same as read.
  707. """
  708. return self.read(size)
  709. def write(self, b):
  710. if self.closed:
  711. raise ValueError("write to closed file")
  712. if isinstance(b, str):
  713. raise TypeError("can't write str to binary stream")
  714. with memoryview(b) as view:
  715. n = view.nbytes # Size of any bytes-like object
  716. if n == 0:
  717. return 0
  718. pos = self._pos
  719. if pos > len(self._buffer):
  720. # Inserts null bytes between the current end of the file
  721. # and the new write position.
  722. padding = b'\x00' * (pos - len(self._buffer))
  723. self._buffer += padding
  724. self._buffer[pos:pos + n] = b
  725. self._pos += n
  726. return n
  727. def seek(self, pos, whence=0):
  728. if self.closed:
  729. raise ValueError("seek on closed file")
  730. try:
  731. pos.__index__
  732. except AttributeError as err:
  733. raise TypeError("an integer is required") from err
  734. if whence == 0:
  735. if pos < 0:
  736. raise ValueError("negative seek position %r" % (pos,))
  737. self._pos = pos
  738. elif whence == 1:
  739. self._pos = max(0, self._pos + pos)
  740. elif whence == 2:
  741. self._pos = max(0, len(self._buffer) + pos)
  742. else:
  743. raise ValueError("unsupported whence value")
  744. return self._pos
  745. def tell(self):
  746. if self.closed:
  747. raise ValueError("tell on closed file")
  748. return self._pos
  749. def truncate(self, pos=None):
  750. if self.closed:
  751. raise ValueError("truncate on closed file")
  752. if pos is None:
  753. pos = self._pos
  754. else:
  755. try:
  756. pos.__index__
  757. except AttributeError as err:
  758. raise TypeError("an integer is required") from err
  759. if pos < 0:
  760. raise ValueError("negative truncate position %r" % (pos,))
  761. del self._buffer[pos:]
  762. return pos
  763. def readable(self):
  764. if self.closed:
  765. raise ValueError("I/O operation on closed file.")
  766. return True
  767. def writable(self):
  768. if self.closed:
  769. raise ValueError("I/O operation on closed file.")
  770. return True
  771. def seekable(self):
  772. if self.closed:
  773. raise ValueError("I/O operation on closed file.")
  774. return True
  775. class BufferedReader(_BufferedIOMixin):
  776. """BufferedReader(raw[, buffer_size])
  777. A buffer for a readable, sequential BaseRawIO object.
  778. The constructor creates a BufferedReader for the given readable raw
  779. stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE
  780. is used.
  781. """
  782. def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
  783. """Create a new buffered reader using the given readable raw IO object.
  784. """
  785. if not raw.readable():
  786. raise OSError('"raw" argument must be readable.')
  787. _BufferedIOMixin.__init__(self, raw)
  788. if buffer_size <= 0:
  789. raise ValueError("invalid buffer size")
  790. self.buffer_size = buffer_size
  791. self._reset_read_buf()
  792. self._read_lock = Lock()
  793. def readable(self):
  794. return self.raw.readable()
  795. def _reset_read_buf(self):
  796. self._read_buf = b""
  797. self._read_pos = 0
  798. def read(self, size=None):
  799. """Read size bytes.
  800. Returns exactly size bytes of data unless the underlying raw IO
  801. stream reaches EOF or if the call would block in non-blocking
  802. mode. If size is negative, read until EOF or until read() would
  803. block.
  804. """
  805. if size is not None and size < -1:
  806. raise ValueError("invalid number of bytes to read")
  807. with self._read_lock:
  808. return self._read_unlocked(size)
  809. def _read_unlocked(self, n=None):
  810. nodata_val = b""
  811. empty_values = (b"", None)
  812. buf = self._read_buf
  813. pos = self._read_pos
  814. # Special case for when the number of bytes to read is unspecified.
  815. if n is None or n == -1:
  816. self._reset_read_buf()
  817. if hasattr(self.raw, 'readall'):
  818. chunk = self.raw.readall()
  819. if chunk is None:
  820. return buf[pos:] or None
  821. else:
  822. return buf[pos:] + chunk
  823. chunks = [buf[pos:]] # Strip the consumed bytes.
  824. current_size = 0
  825. while True:
  826. # Read until EOF or until read() would block.
  827. chunk = self.raw.read()
  828. if chunk in empty_values:
  829. nodata_val = chunk
  830. break
  831. current_size += len(chunk)
  832. chunks.append(chunk)
  833. return b"".join(chunks) or nodata_val
  834. # The number of bytes to read is specified, return at most n bytes.
  835. avail = len(buf) - pos # Length of the available buffered data.
  836. if n <= avail:
  837. # Fast path: the data to read is fully buffered.
  838. self._read_pos += n
  839. return buf[pos:pos+n]
  840. # Slow path: read from the stream until enough bytes are read,
  841. # or until an EOF occurs or until read() would block.
  842. chunks = [buf[pos:]]
  843. wanted = max(self.buffer_size, n)
  844. while avail < n:
  845. chunk = self.raw.read(wanted)
  846. if chunk in empty_values:
  847. nodata_val = chunk
  848. break
  849. avail += len(chunk)
  850. chunks.append(chunk)
  851. # n is more than avail only when an EOF occurred or when
  852. # read() would have blocked.
  853. n = min(n, avail)
  854. out = b"".join(chunks)
  855. self._read_buf = out[n:] # Save the extra data in the buffer.
  856. self._read_pos = 0
  857. return out[:n] if out else nodata_val
  858. def peek(self, size=0):
  859. """Returns buffered bytes without advancing the position.
  860. The argument indicates a desired minimal number of bytes; we
  861. do at most one raw read to satisfy it. We never return more
  862. than self.buffer_size.
  863. """
  864. with self._read_lock:
  865. return self._peek_unlocked(size)
  866. def _peek_unlocked(self, n=0):
  867. want = min(n, self.buffer_size)
  868. have = len(self._read_buf) - self._read_pos
  869. if have < want or have <= 0:
  870. to_read = self.buffer_size - have
  871. current = self.raw.read(to_read)
  872. if current:
  873. self._read_buf = self._read_buf[self._read_pos:] + current
  874. self._read_pos = 0
  875. return self._read_buf[self._read_pos:]
  876. def read1(self, size):
  877. """Reads up to size bytes, with at most one read() system call."""
  878. # Returns up to size bytes. If at least one byte is buffered, we
  879. # only return buffered bytes. Otherwise, we do one raw read.
  880. if size < 0:
  881. raise ValueError("number of bytes to read must be positive")
  882. if size == 0:
  883. return b""
  884. with self._read_lock:
  885. self._peek_unlocked(1)
  886. return self._read_unlocked(
  887. min(size, len(self._read_buf) - self._read_pos))
  888. # Implementing readinto() and readinto1() is not strictly necessary (we
  889. # could rely on the base class that provides an implementation in terms of
  890. # read() and read1()). We do it anyway to keep the _pyio implementation
  891. # similar to the io implementation (which implements the methods for
  892. # performance reasons).
  893. def _readinto(self, buf, read1):
  894. """Read data into *buf* with at most one system call."""
  895. # Need to create a memoryview object of type 'b', otherwise
  896. # we may not be able to assign bytes to it, and slicing it
  897. # would create a new object.
  898. if not isinstance(buf, memoryview):
  899. buf = memoryview(buf)
  900. if buf.nbytes == 0:
  901. return 0
  902. buf = buf.cast('B')
  903. written = 0
  904. with self._read_lock:
  905. while written < len(buf):
  906. # First try to read from internal buffer
  907. avail = min(len(self._read_buf) - self._read_pos, len(buf))
  908. if avail:
  909. buf[written:written+avail] = \
  910. self._read_buf[self._read_pos:self._read_pos+avail]
  911. self._read_pos += avail
  912. written += avail
  913. if written == len(buf):
  914. break
  915. # If remaining space in callers buffer is larger than
  916. # internal buffer, read directly into callers buffer
  917. if len(buf) - written > self.buffer_size:
  918. n = self.raw.readinto(buf[written:])
  919. if not n:
  920. break # eof
  921. written += n
  922. # Otherwise refill internal buffer - unless we're
  923. # in read1 mode and already got some data
  924. elif not (read1 and written):
  925. if not self._peek_unlocked(1):
  926. break # eof
  927. # In readinto1 mode, return as soon as we have some data
  928. if read1 and written:
  929. break
  930. return written
  931. def tell(self):
  932. return _BufferedIOMixin.tell(self) - len(self._read_buf) + self._read_pos
  933. def seek(self, pos, whence=0):
  934. if whence not in valid_seek_flags:
  935. raise ValueError("invalid whence value")
  936. with self._read_lock:
  937. if whence == 1:
  938. pos -= len(self._read_buf) - self._read_pos
  939. pos = _BufferedIOMixin.seek(self, pos, whence)
  940. self._reset_read_buf()
  941. return pos
  942. class BufferedWriter(_BufferedIOMixin):
  943. """A buffer for a writeable sequential RawIO object.
  944. The constructor creates a BufferedWriter for the given writeable raw
  945. stream. If the buffer_size is not given, it defaults to
  946. DEFAULT_BUFFER_SIZE.
  947. """
  948. def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
  949. if not raw.writable():
  950. raise OSError('"raw" argument must be writable.')
  951. _BufferedIOMixin.__init__(self, raw)
  952. if buffer_size <= 0:
  953. raise ValueError("invalid buffer size")
  954. self.buffer_size = buffer_size
  955. self._write_buf = bytearray()
  956. self._write_lock = Lock()
  957. def writable(self):
  958. return self.raw.writable()
  959. def write(self, b):
  960. if self.closed:
  961. raise ValueError("write to closed file")
  962. if isinstance(b, str):
  963. raise TypeError("can't write str to binary stream")
  964. with self._write_lock:
  965. # XXX we can implement some more tricks to try and avoid
  966. # partial writes
  967. if len(self._write_buf) > self.buffer_size:
  968. # We're full, so let's pre-flush the buffer. (This may
  969. # raise BlockingIOError with characters_written == 0.)
  970. self._flush_unlocked()
  971. before = len(self._write_buf)
  972. self._write_buf.extend(b)
  973. written = len(self._write_buf) - before
  974. if len(self._write_buf) > self.buffer_size:
  975. try:
  976. self._flush_unlocked()
  977. except BlockingIOError as e:
  978. if len(self._write_buf) > self.buffer_size:
  979. # We've hit the buffer_size. We have to accept a partial
  980. # write and cut back our buffer.
  981. overage = len(self._write_buf) - self.buffer_size
  982. written -= overage
  983. self._write_buf = self._write_buf[:self.buffer_size]
  984. raise BlockingIOError(e.errno, e.strerror, written)
  985. return written
  986. def truncate(self, pos=None):
  987. with self._write_lock:
  988. self._flush_unlocked()
  989. if pos is None:
  990. pos = self.raw.tell()
  991. return self.raw.truncate(pos)
  992. def flush(self):
  993. with self._write_lock:
  994. self._flush_unlocked()
  995. def _flush_unlocked(self):
  996. if self.closed:
  997. raise ValueError("flush of closed file")
  998. while self._write_buf:
  999. try:
  1000. n = self.raw.write(self._write_buf)
  1001. except BlockingIOError:
  1002. raise RuntimeError("self.raw should implement RawIOBase: it "
  1003. "should not raise BlockingIOError")
  1004. if n is None:
  1005. raise BlockingIOError(
  1006. errno.EAGAIN,
  1007. "write could not complete without blocking", 0)
  1008. if n > len(self._write_buf) or n < 0:
  1009. raise OSError("write() returned incorrect number of bytes")
  1010. del self._write_buf[:n]
  1011. def tell(self):
  1012. return _BufferedIOMixin.tell(self) + len(self._write_buf)
  1013. def seek(self, pos, whence=0):
  1014. if whence not in valid_seek_flags:
  1015. raise ValueError("invalid whence value")
  1016. with self._write_lock:
  1017. self._flush_unlocked()
  1018. return _BufferedIOMixin.seek(self, pos, whence)
  1019. class BufferedRWPair(BufferedIOBase):
  1020. """A buffered reader and writer object together.
  1021. A buffered reader object and buffered writer object put together to
  1022. form a sequential IO object that can read and write. This is typically
  1023. used with a socket or two-way pipe.
  1024. reader and writer are RawIOBase objects that are readable and
  1025. writeable respectively. If the buffer_size is omitted it defaults to
  1026. DEFAULT_BUFFER_SIZE.
  1027. """
  1028. # XXX The usefulness of this (compared to having two separate IO
  1029. # objects) is questionable.
  1030. def __init__(self, reader, writer, buffer_size=DEFAULT_BUFFER_SIZE):
  1031. """Constructor.
  1032. The arguments are two RawIO instances.
  1033. """
  1034. if not reader.readable():
  1035. raise OSError('"reader" argument must be readable.')
  1036. if not writer.writable():
  1037. raise OSError('"writer" argument must be writable.')
  1038. self.reader = BufferedReader(reader, buffer_size)
  1039. self.writer = BufferedWriter(writer, buffer_size)
  1040. def read(self, size=None):
  1041. if size is None:
  1042. size = -1
  1043. return self.reader.read(size)
  1044. def readinto(self, b):
  1045. return self.reader.readinto(b)
  1046. def write(self, b):
  1047. return self.writer.write(b)
  1048. def peek(self, size=0):
  1049. return self.reader.peek(size)
  1050. def read1(self, size):
  1051. return self.reader.read1(size)
  1052. def readinto1(self, b):
  1053. return self.reader.readinto1(b)
  1054. def readable(self):
  1055. return self.reader.readable()
  1056. def writable(self):
  1057. return self.writer.writable()
  1058. def flush(self):
  1059. return self.writer.flush()
  1060. def close(self):
  1061. try:
  1062. self.writer.close()
  1063. finally:
  1064. self.reader.close()
  1065. def isatty(self):
  1066. return self.reader.isatty() or self.writer.isatty()
  1067. @property
  1068. def closed(self):
  1069. return self.writer.closed
  1070. class BufferedRandom(BufferedWriter, BufferedReader):
  1071. """A buffered interface to random access streams.
  1072. The constructor creates a reader and writer for a seekable stream,
  1073. raw, given in the first argument. If the buffer_size is omitted it
  1074. defaults to DEFAULT_BUFFER_SIZE.
  1075. """
  1076. def __init__(self, raw, buffer_size=DEFAULT_BUFFER_SIZE):
  1077. raw._checkSeekable()
  1078. BufferedReader.__init__(self, raw, buffer_size)
  1079. BufferedWriter.__init__(self, raw, buffer_size)
  1080. def seek(self, pos, whence=0):
  1081. if whence not in valid_seek_flags:
  1082. raise ValueError("invalid whence value")
  1083. self.flush()
  1084. if self._read_buf:
  1085. # Undo read ahead.
  1086. with self._read_lock:
  1087. self.raw.seek(self._read_pos - len(self._read_buf), 1)
  1088. # First do the raw seek, then empty the read buffer, so that
  1089. # if the raw seek fails, we don't lose buffered data forever.
  1090. pos = self.raw.seek(pos, whence)
  1091. with self._read_lock:
  1092. self._reset_read_buf()
  1093. if pos < 0:
  1094. raise OSError("seek() returned invalid position")
  1095. return pos
  1096. def tell(self):
  1097. if self._write_buf:
  1098. return BufferedWriter.tell(self)
  1099. else:
  1100. return BufferedReader.tell(self)
  1101. def truncate(self, pos=None):
  1102. if pos is None:
  1103. pos = self.tell()
  1104. # Use seek to flush the read buffer.
  1105. return BufferedWriter.truncate(self, pos)
  1106. def read(self, size=None):
  1107. if size is None:
  1108. size = -1
  1109. self.flush()
  1110. return BufferedReader.read(self, size)
  1111. def readinto(self, b):
  1112. self.flush()
  1113. return BufferedReader.readinto(self, b)
  1114. def peek(self, size=0):
  1115. self.flush()
  1116. return BufferedReader.peek(self, size)
  1117. def read1(self, size):
  1118. self.flush()
  1119. return BufferedReader.read1(self, size)
  1120. def readinto1(self, b):
  1121. self.flush()
  1122. return BufferedReader.readinto1(self, b)
  1123. def write(self, b):
  1124. if self._read_buf:
  1125. # Undo readahead
  1126. with self._read_lock:
  1127. self.raw.seek(self._read_pos - len(self._read_buf), 1)
  1128. self._reset_read_buf()
  1129. return BufferedWriter.write(self, b)
  1130. class FileIO(RawIOBase):
  1131. _fd = -1
  1132. _created = False
  1133. _readable = False
  1134. _writable = False
  1135. _appending = False
  1136. _seekable = None
  1137. _closefd = True
  1138. def __init__(self, file, mode='r', closefd=True, opener=None):
  1139. """Open a file. The mode can be 'r' (default), 'w', 'x' or 'a' for reading,
  1140. writing, exclusive creation or appending. The file will be created if it
  1141. doesn't exist when opened for writing or appending; it will be truncated
  1142. when opened for writing. A FileExistsError will be raised if it already
  1143. exists when opened for creating. Opening a file for creating implies
  1144. writing so this mode behaves in a similar way to 'w'. Add a '+' to the mode
  1145. to allow simultaneous reading and writing. A custom opener can be used by
  1146. passing a callable as *opener*. The underlying file descriptor for the file
  1147. object is then obtained by calling opener with (*name*, *flags*).
  1148. *opener* must return an open file descriptor (passing os.open as *opener*
  1149. results in functionality similar to passing None).
  1150. """
  1151. if self._fd >= 0:
  1152. # Have to close the existing file first.
  1153. try:
  1154. if self._closefd:
  1155. os.close(self._fd)
  1156. finally:
  1157. self._fd = -1
  1158. if isinstance(file, float):
  1159. raise TypeError('integer argument expected, got float')
  1160. if isinstance(file, int):
  1161. fd = file
  1162. if fd < 0:
  1163. raise ValueError('negative file descriptor')
  1164. else:
  1165. fd = -1
  1166. if not isinstance(mode, str):
  1167. raise TypeError('invalid mode: %s' % (mode,))
  1168. if not set(mode) <= set('xrwab+'):
  1169. raise ValueError('invalid mode: %s' % (mode,))
  1170. if sum(c in 'rwax' for c in mode) != 1 or mode.count('+') > 1:
  1171. raise ValueError('Must have exactly one of create/read/write/append '
  1172. 'mode and at most one plus')
  1173. if 'x' in mode:
  1174. self._created = True
  1175. self._writable = True
  1176. flags = os.O_EXCL | os.O_CREAT
  1177. elif 'r' in mode:
  1178. self._readable = True
  1179. flags = 0
  1180. elif 'w' in mode:
  1181. self._writable = True
  1182. flags = os.O_CREAT | os.O_TRUNC
  1183. elif 'a' in mode:
  1184. self._writable = True
  1185. self._appending = True
  1186. flags = os.O_APPEND | os.O_CREAT
  1187. if '+' in mode:
  1188. self._readable = True
  1189. self._writable = True
  1190. if self._readable and self._writable:
  1191. flags |= os.O_RDWR
  1192. elif self._readable:
  1193. flags |= os.O_RDONLY
  1194. else:
  1195. flags |= os.O_WRONLY
  1196. flags |= getattr(os, 'O_BINARY', 0)
  1197. noinherit_flag = (getattr(os, 'O_NOINHERIT', 0) or
  1198. getattr(os, 'O_CLOEXEC', 0))
  1199. flags |= noinherit_flag
  1200. owned_fd = None
  1201. try:
  1202. if fd < 0:
  1203. if not closefd:
  1204. raise ValueError('Cannot use closefd=False with file name')
  1205. if opener is None:
  1206. fd = os.open(file, flags, 0o666)
  1207. else:
  1208. fd = opener(file, flags)
  1209. if not isinstance(fd, int):
  1210. raise TypeError('expected integer from opener')
  1211. if fd < 0:
  1212. raise OSError('Negative file descriptor')
  1213. owned_fd = fd
  1214. if not noinherit_flag:
  1215. os.set_inheritable(fd, False)
  1216. self._closefd = closefd
  1217. fdfstat = os.fstat(fd)
  1218. try:
  1219. if stat.S_ISDIR(fdfstat.st_mode):
  1220. raise IsADirectoryError(errno.EISDIR,
  1221. os.strerror(errno.EISDIR), file)
  1222. except AttributeError:
  1223. # Ignore the AttribueError if stat.S_ISDIR or errno.EISDIR
  1224. # don't exist.
  1225. pass
  1226. self._blksize = getattr(fdfstat, 'st_blksize', 0)
  1227. if self._blksize <= 1:
  1228. self._blksize = DEFAULT_BUFFER_SIZE
  1229. if _setmode:
  1230. # don't translate newlines (\r\n <=> \n)
  1231. _setmode(fd, os.O_BINARY)
  1232. self.name = file
  1233. if self._appending:
  1234. # For consistent behaviour, we explicitly seek to the
  1235. # end of file (otherwise, it might be done only on the
  1236. # first write()).
  1237. os.lseek(fd, 0, SEEK_END)
  1238. except:
  1239. if owned_fd is not None:
  1240. os.close(owned_fd)
  1241. raise
  1242. self._fd = fd
  1243. def __del__(self):
  1244. if self._fd >= 0 and self._closefd and not self.closed:
  1245. import warnings
  1246. warnings.warn('unclosed file %r' % (self,), ResourceWarning,
  1247. stacklevel=2)
  1248. self.close()
  1249. def __getstate__(self):
  1250. raise TypeError("cannot serialize '%s' object", self.__class__.__name__)
  1251. def __repr__(self):
  1252. class_name = '%s.%s' % (self.__class__.__module__,
  1253. self.__class__.__qualname__)
  1254. if self.closed:
  1255. return '<%s [closed]>' % class_name
  1256. try:
  1257. name = self.name
  1258. except AttributeError:
  1259. return ('<%s fd=%d mode=%r closefd=%r>' %
  1260. (class_name, self._fd, self.mode, self._closefd))
  1261. else:
  1262. return ('<%s name=%r mode=%r closefd=%r>' %
  1263. (class_name, name, self.mode, self._closefd))
  1264. def _checkReadable(self):
  1265. if not self._readable:
  1266. raise UnsupportedOperation('File not open for reading')
  1267. def _checkWritable(self, msg=None):
  1268. if not self._writable:
  1269. raise UnsupportedOperation('File not open for writing')
  1270. def read(self, size=None):
  1271. """Read at most size bytes, returned as bytes.
  1272. Only makes one system call, so less data may be returned than requested
  1273. In non-blocking mode, returns None if no data is available.
  1274. Return an empty bytes object at EOF.
  1275. """
  1276. self._checkClosed()
  1277. self._checkReadable()
  1278. if size is None or size < 0:
  1279. return self.readall()
  1280. try:
  1281. return os.read(self._fd, size)
  1282. except BlockingIOError:
  1283. return None
  1284. def readall(self):
  1285. """Read all data from the file, returned as bytes.
  1286. In non-blocking mode, returns as much as is immediately available,
  1287. or None if no data is available. Return an empty bytes object at EOF.
  1288. """
  1289. self._checkClosed()
  1290. self._checkReadable()
  1291. bufsize = DEFAULT_BUFFER_SIZE
  1292. try:
  1293. pos = os.lseek(self._fd, 0, SEEK_CUR)
  1294. end = os.fstat(self._fd).st_size
  1295. if end >= pos:
  1296. bufsize = end - pos + 1
  1297. except OSError:
  1298. pass
  1299. result = bytearray()
  1300. while True:
  1301. if len(result) >= bufsize:
  1302. bufsize = len(result)
  1303. bufsize += max(bufsize, DEFAULT_BUFFER_SIZE)
  1304. n = bufsize - len(result)
  1305. try:
  1306. chunk = os.read(self._fd, n)
  1307. except BlockingIOError:
  1308. if result:
  1309. break
  1310. return None
  1311. if not chunk: # reached the end of the file
  1312. break
  1313. result += chunk
  1314. return bytes(result)
  1315. def readinto(self, b):
  1316. """Same as RawIOBase.readinto()."""
  1317. m = memoryview(b).cast('B')
  1318. data = self.read(len(m))
  1319. n = len(data)
  1320. m[:n] = data
  1321. return n
  1322. def write(self, b):
  1323. """Write bytes b to file, return number written.
  1324. Only makes one system call, so not all of the data may be written.
  1325. The number of bytes actually written is returned. In non-blocking mode,
  1326. returns None if the write would block.
  1327. """
  1328. self._checkClosed()
  1329. self._checkWritable()
  1330. try:
  1331. return os.write(self._fd, b)
  1332. except BlockingIOError:
  1333. return None
  1334. def seek(self, pos, whence=SEEK_SET):
  1335. """Move to new file position.
  1336. Argument offset is a byte count. Optional argument whence defaults to
  1337. SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
  1338. are SEEK_CUR or 1 (move relative to current position, positive or negative),
  1339. and SEEK_END or 2 (move relative to end of file, usually negative, although
  1340. many platforms allow seeking beyond the end of a file).
  1341. Note that not all file objects are seekable.
  1342. """
  1343. if isinstance(pos, float):
  1344. raise TypeError('an integer is required')
  1345. self._checkClosed()
  1346. return os.lseek(self._fd, pos, whence)
  1347. def tell(self):
  1348. """tell() -> int. Current file position.
  1349. Can raise OSError for non seekable files."""
  1350. self._checkClosed()
  1351. return os.lseek(self._fd, 0, SEEK_CUR)
  1352. def truncate(self, size=None):
  1353. """Truncate the file to at most size bytes.
  1354. Size defaults to the current file position, as returned by tell().
  1355. The current file position is changed to the value of size.
  1356. """
  1357. self._checkClosed()
  1358. self._checkWritable()
  1359. if size is None:
  1360. size = self.tell()
  1361. os.ftruncate(self._fd, size)
  1362. return size
  1363. def close(self):
  1364. """Close the file.
  1365. A closed file cannot be used for further I/O operations. close() may be
  1366. called more than once without error.
  1367. """
  1368. if not self.closed:
  1369. try:
  1370. if self._closefd:
  1371. os.close(self._fd)
  1372. finally:
  1373. super().close()
  1374. def seekable(self):
  1375. """True if file supports random-access."""
  1376. self._checkClosed()
  1377. if self._seekable is None:
  1378. try:
  1379. self.tell()
  1380. except OSError:
  1381. self._seekable = False
  1382. else:
  1383. self._seekable = True
  1384. return self._seekable
  1385. def readable(self):
  1386. """True if file was opened in a read mode."""
  1387. self._checkClosed()
  1388. return self._readable
  1389. def writable(self):
  1390. """True if file was opened in a write mode."""
  1391. self._checkClosed()
  1392. return self._writable
  1393. def fileno(self):
  1394. """Return the underlying file descriptor (an integer)."""
  1395. self._checkClosed()
  1396. return self._fd
  1397. def isatty(self):
  1398. """True if the file is connected to a TTY device."""
  1399. self._checkClosed()
  1400. return os.isatty(self._fd)
  1401. @property
  1402. def closefd(self):
  1403. """True if the file descriptor will be closed by close()."""
  1404. return self._closefd
  1405. @property
  1406. def mode(self):
  1407. """String giving the file mode"""
  1408. if self._created:
  1409. if self._readable:
  1410. return 'xb+'
  1411. else:
  1412. return 'xb'
  1413. elif self._appending:
  1414. if self._readable:
  1415. return 'ab+'
  1416. else:
  1417. return 'ab'
  1418. elif self._readable:
  1419. if self._writable:
  1420. return 'rb+'
  1421. else:
  1422. return 'rb'
  1423. else:
  1424. return 'wb'
  1425. class TextIOBase(IOBase):
  1426. """Base class for text I/O.
  1427. This class provides a character and line based interface to stream
  1428. I/O. There is no readinto method because Python's character strings
  1429. are immutable. There is no public constructor.
  1430. """
  1431. def read(self, size=-1):
  1432. """Read at most size characters from stream, where size is an int.
  1433. Read from underlying buffer until we have size characters or we hit EOF.
  1434. If size is negative or omitted, read until EOF.
  1435. Returns a string.
  1436. """
  1437. self._unsupported("read")
  1438. def write(self, s):
  1439. """Write string s to stream and returning an int."""
  1440. self._unsupported("write")
  1441. def truncate(self, pos=None):
  1442. """Truncate size to pos, where pos is an int."""
  1443. self._unsupported("truncate")
  1444. def readline(self):
  1445. """Read until newline or EOF.
  1446. Returns an empty string if EOF is hit immediately.
  1447. """
  1448. self._unsupported("readline")
  1449. def detach(self):
  1450. """
  1451. Separate the underlying buffer from the TextIOBase and return it.
  1452. After the underlying buffer has been detached, the TextIO is in an
  1453. unusable state.
  1454. """
  1455. self._unsupported("detach")
  1456. @property
  1457. def encoding(self):
  1458. """Subclasses should override."""
  1459. return None
  1460. @property
  1461. def newlines(self):
  1462. """Line endings translated so far.
  1463. Only line endings translated during reading are considered.
  1464. Subclasses should override.
  1465. """
  1466. return None
  1467. @property
  1468. def errors(self):
  1469. """Error setting of the decoder or encoder.
  1470. Subclasses should override."""
  1471. return None
  1472. io.TextIOBase.register(TextIOBase)
  1473. class IncrementalNewlineDecoder(codecs.IncrementalDecoder):
  1474. r"""Codec used when reading a file in universal newlines mode. It wraps
  1475. another incremental decoder, translating \r\n and \r into \n. It also
  1476. records the types of newlines encountered. When used with
  1477. translate=False, it ensures that the newline sequence is returned in
  1478. one piece.
  1479. """
  1480. def __init__(self, decoder, translate, errors='strict'):
  1481. codecs.IncrementalDecoder.__init__(self, errors=errors)
  1482. self.translate = translate
  1483. self.decoder = decoder
  1484. self.seennl = 0
  1485. self.pendingcr = False
  1486. def decode(self, input, final=False):
  1487. # decode input (with the eventual \r from a previous pass)
  1488. if self.decoder is None:
  1489. output = input
  1490. else:
  1491. output = self.decoder.decode(input, final=final)
  1492. if self.pendingcr and (output or final):
  1493. output = "\r" + output
  1494. self.pendingcr = False
  1495. # retain last \r even when not translating data:
  1496. # then readline() is sure to get \r\n in one pass
  1497. if output.endswith("\r") and not final:
  1498. output = output[:-1]
  1499. self.pendingcr = True
  1500. # Record which newlines are read
  1501. crlf = output.count('\r\n')
  1502. cr = output.count('\r') - crlf
  1503. lf = output.count('\n') - crlf
  1504. self.seennl |= (lf and self._LF) | (cr and self._CR) \
  1505. | (crlf and self._CRLF)
  1506. if self.translate:
  1507. if crlf:
  1508. output = output.replace("\r\n", "\n")
  1509. if cr:
  1510. output = output.replace("\r", "\n")
  1511. return output
  1512. def getstate(self):
  1513. if self.decoder is None:
  1514. buf = b""
  1515. flag = 0
  1516. else:
  1517. buf, flag = self.decoder.getstate()
  1518. flag <<= 1
  1519. if self.pendingcr:
  1520. flag |= 1
  1521. return buf, flag
  1522. def setstate(self, state):
  1523. buf, flag = state
  1524. self.pendingcr = bool(flag & 1)
  1525. if self.decoder is not None:
  1526. self.decoder.setstate((buf, flag >> 1))
  1527. def reset(self):
  1528. self.seennl = 0
  1529. self.pendingcr = False
  1530. if self.decoder is not None:
  1531. self.decoder.reset()
  1532. _LF = 1
  1533. _CR = 2
  1534. _CRLF = 4
  1535. @property
  1536. def newlines(self):
  1537. return (None,
  1538. "\n",
  1539. "\r",
  1540. ("\r", "\n"),
  1541. "\r\n",
  1542. ("\n", "\r\n"),
  1543. ("\r", "\r\n"),
  1544. ("\r", "\n", "\r\n")
  1545. )[self.seennl]
  1546. class TextIOWrapper(TextIOBase):
  1547. r"""Character and line based layer over a BufferedIOBase object, buffer.
  1548. encoding gives the name of the encoding that the stream will be
  1549. decoded or encoded with. It defaults to locale.getpreferredencoding(False).
  1550. errors determines the strictness of encoding and decoding (see the
  1551. codecs.register) and defaults to "strict".
  1552. newline can be None, '', '\n', '\r', or '\r\n'. It controls the
  1553. handling of line endings. If it is None, universal newlines is
  1554. enabled. With this enabled, on input, the lines endings '\n', '\r',
  1555. or '\r\n' are translated to '\n' before being returned to the
  1556. caller. Conversely, on output, '\n' is translated to the system
  1557. default line separator, os.linesep. If newline is any other of its
  1558. legal values, that newline becomes the newline when the file is read
  1559. and it is returned untranslated. On output, '\n' is converted to the
  1560. newline.
  1561. If line_buffering is True, a call to flush is implied when a call to
  1562. write contains a newline character.
  1563. """
  1564. _CHUNK_SIZE = 2048
  1565. # The write_through argument has no effect here since this
  1566. # implementation always writes through. The argument is present only
  1567. # so that the signature can match the signature of the C version.
  1568. def __init__(self, buffer, encoding=None, errors=None, newline=None,
  1569. line_buffering=False, write_through=False):
  1570. if newline is not None and not isinstance(newline, str):
  1571. raise TypeError("illegal newline type: %r" % (type(newline),))
  1572. if newline not in (None, "", "\n", "\r", "\r\n"):
  1573. raise ValueError("illegal newline value: %r" % (newline,))
  1574. if encoding is None:
  1575. try:
  1576. encoding = os.device_encoding(buffer.fileno())
  1577. except (AttributeError, UnsupportedOperation):
  1578. pass
  1579. if encoding is None:
  1580. try:
  1581. import locale
  1582. except ImportError:
  1583. # Importing locale may fail if Python is being built
  1584. encoding = "ascii"
  1585. else:
  1586. encoding = locale.getpreferredencoding(False)
  1587. if not isinstance(encoding, str):
  1588. raise ValueError("invalid encoding: %r" % encoding)
  1589. if not codecs.lookup(encoding)._is_text_encoding:
  1590. msg = ("%r is not a text encoding; "
  1591. "use codecs.open() to handle arbitrary codecs")
  1592. raise LookupError(msg % encoding)
  1593. if errors is None:
  1594. errors = "strict"
  1595. else:
  1596. if not isinstance(errors, str):
  1597. raise ValueError("invalid errors: %r" % errors)
  1598. self._buffer = buffer
  1599. self._line_buffering = line_buffering
  1600. self._encoding = encoding
  1601. self._errors = errors
  1602. self._readuniversal = not newline
  1603. self._readtranslate = newline is None
  1604. self._readnl = newline
  1605. self._writetranslate = newline != ''
  1606. self._writenl = newline or os.linesep
  1607. self._encoder = None
  1608. self._decoder = None
  1609. self._decoded_chars = '' # buffer for text returned from decoder
  1610. self._decoded_chars_used = 0 # offset into _decoded_chars for read()
  1611. self._snapshot = None # info for reconstructing decoder state
  1612. self._seekable = self._telling = self.buffer.seekable()
  1613. self._has_read1 = hasattr(self.buffer, 'read1')
  1614. self._b2cratio = 0.0
  1615. if self._seekable and self.writable():
  1616. position = self.buffer.tell()
  1617. if position != 0:
  1618. try:
  1619. self._get_encoder().setstate(0)
  1620. except LookupError:
  1621. # Sometimes the encoder doesn't exist
  1622. pass
  1623. # self._snapshot is either None, or a tuple (dec_flags, next_input)
  1624. # where dec_flags is the second (integer) item of the decoder state
  1625. # and next_input is the chunk of input bytes that comes next after the
  1626. # snapshot point. We use this to reconstruct decoder states in tell().
  1627. # Naming convention:
  1628. # - "bytes_..." for integer variables that count input bytes
  1629. # - "chars_..." for integer variables that count decoded characters
  1630. def __repr__(self):
  1631. result = "<{}.{}".format(self.__class__.__module__,
  1632. self.__class__.__qualname__)
  1633. try:
  1634. name = self.name
  1635. except Exception:
  1636. pass
  1637. else:
  1638. result += " name={0!r}".format(name)
  1639. try:
  1640. mode = self.mode
  1641. except Exception:
  1642. pass
  1643. else:
  1644. result += " mode={0!r}".format(mode)
  1645. return result + " encoding={0!r}>".format(self.encoding)
  1646. @property
  1647. def encoding(self):
  1648. return self._encoding
  1649. @property
  1650. def errors(self):
  1651. return self._errors
  1652. @property
  1653. def line_buffering(self):
  1654. return self._line_buffering
  1655. @property
  1656. def buffer(self):
  1657. return self._buffer
  1658. def seekable(self):
  1659. if self.closed:
  1660. raise ValueError("I/O operation on closed file.")
  1661. return self._seekable
  1662. def readable(self):
  1663. return self.buffer.readable()
  1664. def writable(self):
  1665. return self.buffer.writable()
  1666. def flush(self):
  1667. self.buffer.flush()
  1668. self._telling = self._seekable
  1669. def close(self):
  1670. if self.buffer is not None and not self.closed:
  1671. try:
  1672. self.flush()
  1673. finally:
  1674. self.buffer.close()
  1675. @property
  1676. def closed(self):
  1677. return self.buffer.closed
  1678. @property
  1679. def name(self):
  1680. return self.buffer.name
  1681. def fileno(self):
  1682. return self.buffer.fileno()
  1683. def isatty(self):
  1684. return self.buffer.isatty()
  1685. def write(self, s):
  1686. 'Write data, where s is a str'
  1687. if self.closed:
  1688. raise ValueError("write to closed file")
  1689. if not isinstance(s, str):
  1690. raise TypeError("can't write %s to text stream" %
  1691. s.__class__.__name__)
  1692. length = len(s)
  1693. haslf = (self._writetranslate or self._line_buffering) and "\n" in s
  1694. if haslf and self._writetranslate and self._writenl != "\n":
  1695. s = s.replace("\n", self._writenl)
  1696. encoder = self._encoder or self._get_encoder()
  1697. # XXX What if we were just reading?
  1698. b = encoder.encode(s)
  1699. self.buffer.write(b)
  1700. if self._line_buffering and (haslf or "\r" in s):
  1701. self.flush()
  1702. self._snapshot = None
  1703. if self._decoder:
  1704. self._decoder.reset()
  1705. return length
  1706. def _get_encoder(self):
  1707. make_encoder = codecs.getincrementalencoder(self._encoding)
  1708. self._encoder = make_encoder(self._errors)
  1709. return self._encoder
  1710. def _get_decoder(self):
  1711. make_decoder = codecs.getincrementaldecoder(self._encoding)
  1712. decoder = make_decoder(self._errors)
  1713. if self._readuniversal:
  1714. decoder = IncrementalNewlineDecoder(decoder, self._readtranslate)
  1715. self._decoder = decoder
  1716. return decoder
  1717. # The following three methods implement an ADT for _decoded_chars.
  1718. # Text returned from the decoder is buffered here until the client
  1719. # requests it by calling our read() or readline() method.
  1720. def _set_decoded_chars(self, chars):
  1721. """Set the _decoded_chars buffer."""
  1722. self._decoded_chars = chars
  1723. self._decoded_chars_used = 0
  1724. def _get_decoded_chars(self, n=None):
  1725. """Advance into the _decoded_chars buffer."""
  1726. offset = self._decoded_chars_used
  1727. if n is None:
  1728. chars = self._decoded_chars[offset:]
  1729. else:
  1730. chars = self._decoded_chars[offset:offset + n]
  1731. self._decoded_chars_used += len(chars)
  1732. return chars
  1733. def _rewind_decoded_chars(self, n):
  1734. """Rewind the _decoded_chars buffer."""
  1735. if self._decoded_chars_used < n:
  1736. raise AssertionError("rewind decoded_chars out of bounds")
  1737. self._decoded_chars_used -= n
  1738. def _read_chunk(self):
  1739. """
  1740. Read and decode the next chunk of data from the BufferedReader.
  1741. """
  1742. # The return value is True unless EOF was reached. The decoded
  1743. # string is placed in self._decoded_chars (replacing its previous
  1744. # value). The entire input chunk is sent to the decoder, though
  1745. # some of it may remain buffered in the decoder, yet to be
  1746. # converted.
  1747. if self._decoder is None:
  1748. raise ValueError("no decoder")
  1749. if self._telling:
  1750. # To prepare for tell(), we need to snapshot a point in the
  1751. # file where the decoder's input buffer is empty.
  1752. dec_buffer, dec_flags = self._decoder.getstate()
  1753. # Given this, we know there was a valid snapshot point
  1754. # len(dec_buffer) bytes ago with decoder state (b'', dec_flags).
  1755. # Read a chunk, decode it, and put the result in self._decoded_chars.
  1756. if self._has_read1:
  1757. input_chunk = self.buffer.read1(self._CHUNK_SIZE)
  1758. else:
  1759. input_chunk = self.buffer.read(self._CHUNK_SIZE)
  1760. eof = not input_chunk
  1761. decoded_chars = self._decoder.decode(input_chunk, eof)
  1762. self._set_decoded_chars(decoded_chars)
  1763. if decoded_chars:
  1764. self._b2cratio = len(input_chunk) / len(self._decoded_chars)
  1765. else:
  1766. self._b2cratio = 0.0
  1767. if self._telling:
  1768. # At the snapshot point, len(dec_buffer) bytes before the read,
  1769. # the next input to be decoded is dec_buffer + input_chunk.
  1770. self._snapshot = (dec_flags, dec_buffer + input_chunk)
  1771. return not eof
  1772. def _pack_cookie(self, position, dec_flags=0,
  1773. bytes_to_feed=0, need_eof=0, chars_to_skip=0):
  1774. # The meaning of a tell() cookie is: seek to position, set the
  1775. # decoder flags to dec_flags, read bytes_to_feed bytes, feed them
  1776. # into the decoder with need_eof as the EOF flag, then skip
  1777. # chars_to_skip characters of the decoded result. For most simple
  1778. # decoders, tell() will often just give a byte offset in the file.
  1779. return (position | (dec_flags<<64) | (bytes_to_feed<<128) |
  1780. (chars_to_skip<<192) | bool(need_eof)<<256)
  1781. def _unpack_cookie(self, bigint):
  1782. rest, position = divmod(bigint, 1<<64)
  1783. rest, dec_flags = divmod(rest, 1<<64)
  1784. rest, bytes_to_feed = divmod(rest, 1<<64)
  1785. need_eof, chars_to_skip = divmod(rest, 1<<64)
  1786. return position, dec_flags, bytes_to_feed, need_eof, chars_to_skip
  1787. def tell(self):
  1788. if not self._seekable:
  1789. raise UnsupportedOperation("underlying stream is not seekable")
  1790. if not self._telling:
  1791. raise OSError("telling position disabled by next() call")
  1792. self.flush()
  1793. position = self.buffer.tell()
  1794. decoder = self._decoder
  1795. if decoder is None or self._snapshot is None:
  1796. if self._decoded_chars:
  1797. # This should never happen.
  1798. raise AssertionError("pending decoded text")
  1799. return position
  1800. # Skip backward to the snapshot point (see _read_chunk).
  1801. dec_flags, next_input = self._snapshot
  1802. position -= len(next_input)
  1803. # How many decoded characters have been used up since the snapshot?
  1804. chars_to_skip = self._decoded_chars_used
  1805. if chars_to_skip == 0:
  1806. # We haven't moved from the snapshot point.
  1807. return self._pack_cookie(position, dec_flags)
  1808. # Starting from the snapshot position, we will walk the decoder
  1809. # forward until it gives us enough decoded characters.
  1810. saved_state = decoder.getstate()
  1811. try:
  1812. # Fast search for an acceptable start point, close to our
  1813. # current pos.
  1814. # Rationale: calling decoder.decode() has a large overhead
  1815. # regardless of chunk size; we want the number of such calls to
  1816. # be O(1) in most situations (common decoders, non-crazy input).
  1817. # Actually, it will be exactly 1 for fixed-size codecs (all
  1818. # 8-bit codecs, also UTF-16 and UTF-32).
  1819. skip_bytes = int(self._b2cratio * chars_to_skip)
  1820. skip_back = 1
  1821. assert skip_bytes <= len(next_input)
  1822. while skip_bytes > 0:
  1823. decoder.setstate((b'', dec_flags))
  1824. # Decode up to temptative start point
  1825. n = len(decoder.decode(next_input[:skip_bytes]))
  1826. if n <= chars_to_skip:
  1827. b, d = decoder.getstate()
  1828. if not b:
  1829. # Before pos and no bytes buffered in decoder => OK
  1830. dec_flags = d
  1831. chars_to_skip -= n
  1832. break
  1833. # Skip back by buffered amount and reset heuristic
  1834. skip_bytes -= len(b)
  1835. skip_back = 1
  1836. else:
  1837. # We're too far ahead, skip back a bit
  1838. skip_bytes -= skip_back
  1839. skip_back = skip_back * 2
  1840. else:
  1841. skip_bytes = 0
  1842. decoder.setstate((b'', dec_flags))
  1843. # Note our initial start point.
  1844. start_pos = position + skip_bytes
  1845. start_flags = dec_flags
  1846. if chars_to_skip == 0:
  1847. # We haven't moved from the start point.
  1848. return self._pack_cookie(start_pos, start_flags)
  1849. # Feed the decoder one byte at a time. As we go, note the
  1850. # nearest "safe start point" before the current location
  1851. # (a point where the decoder has nothing buffered, so seek()
  1852. # can safely start from there and advance to this location).
  1853. bytes_fed = 0
  1854. need_eof = 0
  1855. # Chars decoded since `start_pos`
  1856. chars_decoded = 0
  1857. for i in range(skip_bytes, len(next_input)):
  1858. bytes_fed += 1
  1859. chars_decoded += len(decoder.decode(next_input[i:i+1]))
  1860. dec_buffer, dec_flags = decoder.getstate()
  1861. if not dec_buffer and chars_decoded <= chars_to_skip:
  1862. # Decoder buffer is empty, so this is a safe start point.
  1863. start_pos += bytes_fed
  1864. chars_to_skip -= chars_decoded
  1865. start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
  1866. if chars_decoded >= chars_to_skip:
  1867. break
  1868. else:
  1869. # We didn't get enough decoded data; signal EOF to get more.
  1870. chars_decoded += len(decoder.decode(b'', final=True))
  1871. need_eof = 1
  1872. if chars_decoded < chars_to_skip:
  1873. raise OSError("can't reconstruct logical file position")
  1874. # The returned cookie corresponds to the last safe start point.
  1875. return self._pack_cookie(
  1876. start_pos, start_flags, bytes_fed, need_eof, chars_to_skip)
  1877. finally:
  1878. decoder.setstate(saved_state)
  1879. def truncate(self, pos=None):
  1880. self.flush()
  1881. if pos is None:
  1882. pos = self.tell()
  1883. return self.buffer.truncate(pos)
  1884. def detach(self):
  1885. if self.buffer is None:
  1886. raise ValueError("buffer is already detached")
  1887. self.flush()
  1888. buffer = self._buffer
  1889. self._buffer = None
  1890. return buffer
  1891. def seek(self, cookie, whence=0):
  1892. def _reset_encoder(position):
  1893. """Reset the encoder (merely useful for proper BOM handling)"""
  1894. try:
  1895. encoder = self._encoder or self._get_encoder()
  1896. except LookupError:
  1897. # Sometimes the encoder doesn't exist
  1898. pass
  1899. else:
  1900. if position != 0:
  1901. encoder.setstate(0)
  1902. else:
  1903. encoder.reset()
  1904. if self.closed:
  1905. raise ValueError("tell on closed file")
  1906. if not self._seekable:
  1907. raise UnsupportedOperation("underlying stream is not seekable")
  1908. if whence == 1: # seek relative to current position
  1909. if cookie != 0:
  1910. raise UnsupportedOperation("can't do nonzero cur-relative seeks")
  1911. # Seeking to the current position should attempt to
  1912. # sync the underlying buffer with the current position.
  1913. whence = 0
  1914. cookie = self.tell()
  1915. if whence == 2: # seek relative to end of file
  1916. if cookie != 0:
  1917. raise UnsupportedOperation("can't do nonzero end-relative seeks")
  1918. self.flush()
  1919. position = self.buffer.seek(0, 2)
  1920. self._set_decoded_chars('')
  1921. self._snapshot = None
  1922. if self._decoder:
  1923. self._decoder.reset()
  1924. _reset_encoder(position)
  1925. return position
  1926. if whence != 0:
  1927. raise ValueError("unsupported whence (%r)" % (whence,))
  1928. if cookie < 0:
  1929. raise ValueError("negative seek position %r" % (cookie,))
  1930. self.flush()
  1931. # The strategy of seek() is to go back to the safe start point
  1932. # and replay the effect of read(chars_to_skip) from there.
  1933. start_pos, dec_flags, bytes_to_feed, need_eof, chars_to_skip = \
  1934. self._unpack_cookie(cookie)
  1935. # Seek back to the safe start point.
  1936. self.buffer.seek(start_pos)
  1937. self._set_decoded_chars('')
  1938. self._snapshot = None
  1939. # Restore the decoder to its state from the safe start point.
  1940. if cookie == 0 and self._decoder:
  1941. self._decoder.reset()
  1942. elif self._decoder or dec_flags or chars_to_skip:
  1943. self._decoder = self._decoder or self._get_decoder()
  1944. self._decoder.setstate((b'', dec_flags))
  1945. self._snapshot = (dec_flags, b'')
  1946. if chars_to_skip:
  1947. # Just like _read_chunk, feed the decoder and save a snapshot.
  1948. input_chunk = self.buffer.read(bytes_to_feed)
  1949. self._set_decoded_chars(
  1950. self._decoder.decode(input_chunk, need_eof))
  1951. self._snapshot = (dec_flags, input_chunk)
  1952. # Skip chars_to_skip of the decoded characters.
  1953. if len(self._decoded_chars) < chars_to_skip:
  1954. raise OSError("can't restore logical file position")
  1955. self._decoded_chars_used = chars_to_skip
  1956. _reset_encoder(cookie)
  1957. return cookie
  1958. def read(self, size=None):
  1959. self._checkReadable()
  1960. if size is None:
  1961. size = -1
  1962. decoder = self._decoder or self._get_decoder()
  1963. try:
  1964. size.__index__
  1965. except AttributeError as err:
  1966. raise TypeError("an integer is required") from err
  1967. if size < 0:
  1968. # Read everything.
  1969. result = (self._get_decoded_chars() +
  1970. decoder.decode(self.buffer.read(), final=True))
  1971. self._set_decoded_chars('')
  1972. self._snapshot = None
  1973. return result
  1974. else:
  1975. # Keep reading chunks until we have size characters to return.
  1976. eof = False
  1977. result = self._get_decoded_chars(size)
  1978. while len(result) < size and not eof:
  1979. eof = not self._read_chunk()
  1980. result += self._get_decoded_chars(size - len(result))
  1981. return result
  1982. def __next__(self):
  1983. self._telling = False
  1984. line = self.readline()
  1985. if not line:
  1986. self._snapshot = None
  1987. self._telling = self._seekable
  1988. raise StopIteration
  1989. return line
  1990. def readline(self, size=None):
  1991. if self.closed:
  1992. raise ValueError("read from closed file")
  1993. if size is None:
  1994. size = -1
  1995. elif not isinstance(size, int):
  1996. raise TypeError("size must be an integer")
  1997. # Grab all the decoded text (we will rewind any extra bits later).
  1998. line = self._get_decoded_chars()
  1999. start = 0
  2000. # Make the decoder if it doesn't already exist.
  2001. if not self._decoder:
  2002. self._get_decoder()
  2003. pos = endpos = None
  2004. while True:
  2005. if self._readtranslate:
  2006. # Newlines are already translated, only search for \n
  2007. pos = line.find('\n', start)
  2008. if pos >= 0:
  2009. endpos = pos + 1
  2010. break
  2011. else:
  2012. start = len(line)
  2013. elif self._readuniversal:
  2014. # Universal newline search. Find any of \r, \r\n, \n
  2015. # The decoder ensures that \r\n are not split in two pieces
  2016. # In C we'd look for these in parallel of course.
  2017. nlpos = line.find("\n", start)
  2018. crpos = line.find("\r", start)
  2019. if crpos == -1:
  2020. if nlpos == -1:
  2021. # Nothing found
  2022. start = len(line)
  2023. else:
  2024. # Found \n
  2025. endpos = nlpos + 1
  2026. break
  2027. elif nlpos == -1:
  2028. # Found lone \r
  2029. endpos = crpos + 1
  2030. break
  2031. elif nlpos < crpos:
  2032. # Found \n
  2033. endpos = nlpos + 1
  2034. break
  2035. elif nlpos == crpos + 1:
  2036. # Found \r\n
  2037. endpos = crpos + 2
  2038. break
  2039. else:
  2040. # Found \r
  2041. endpos = crpos + 1
  2042. break
  2043. else:
  2044. # non-universal
  2045. pos = line.find(self._readnl)
  2046. if pos >= 0:
  2047. endpos = pos + len(self._readnl)
  2048. break
  2049. if size >= 0 and len(line) >= size:
  2050. endpos = size # reached length size
  2051. break
  2052. # No line ending seen yet - get more data'
  2053. while self._read_chunk():
  2054. if self._decoded_chars:
  2055. break
  2056. if self._decoded_chars:
  2057. line += self._get_decoded_chars()
  2058. else:
  2059. # end of file
  2060. self._set_decoded_chars('')
  2061. self._snapshot = None
  2062. return line
  2063. if size >= 0 and endpos > size:
  2064. endpos = size # don't exceed size
  2065. # Rewind _decoded_chars to just after the line ending we found.
  2066. self._rewind_decoded_chars(len(line) - endpos)
  2067. return line[:endpos]
  2068. @property
  2069. def newlines(self):
  2070. return self._decoder.newlines if self._decoder else None
  2071. class StringIO(TextIOWrapper):
  2072. """Text I/O implementation using an in-memory buffer.
  2073. The initial_value argument sets the value of object. The newline
  2074. argument is like the one of TextIOWrapper's constructor.
  2075. """
  2076. def __init__(self, initial_value="", newline="\n"):
  2077. super(StringIO, self).__init__(BytesIO(),
  2078. encoding="utf-8",
  2079. errors="surrogatepass",
  2080. newline=newline)
  2081. # Issue #5645: make universal newlines semantics the same as in the
  2082. # C version, even under Windows.
  2083. if newline is None:
  2084. self._writetranslate = False
  2085. if initial_value is not None:
  2086. if not isinstance(initial_value, str):
  2087. raise TypeError("initial_value must be str or None, not {0}"
  2088. .format(type(initial_value).__name__))
  2089. self.write(initial_value)
  2090. self.seek(0)
  2091. def getvalue(self):
  2092. self.flush()
  2093. decoder = self._decoder or self._get_decoder()
  2094. old_state = decoder.getstate()
  2095. decoder.reset()
  2096. try:
  2097. return decoder.decode(self.buffer.getvalue(), final=True)
  2098. finally:
  2099. decoder.setstate(old_state)
  2100. def __repr__(self):
  2101. # TextIOWrapper tells the encoding in its repr. In StringIO,
  2102. # that's an implementation detail.
  2103. return object.__repr__(self)
  2104. @property
  2105. def errors(self):
  2106. return None
  2107. @property
  2108. def encoding(self):
  2109. return None
  2110. def detach(self):
  2111. # This doesn't make sense on StringIO.
  2112. self._unsupported("detach")