_pyio.py 89 KB

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