_pyio.py 91 KB

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