_pyio.py 91 KB

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