_pyio.py 91 KB

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