_pyio.py 92 KB

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