core.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. from __future__ import annotations
  2. import io
  3. import logging
  4. import os
  5. import re
  6. from glob import has_magic
  7. from pathlib import Path
  8. # for backwards compat, we export cache things from here too
  9. from fsspec.caching import ( # noqa: F401
  10. BaseCache,
  11. BlockCache,
  12. BytesCache,
  13. MMapCache,
  14. ReadAheadCache,
  15. caches,
  16. )
  17. from fsspec.compression import compr
  18. from fsspec.config import conf
  19. from fsspec.registry import filesystem, get_filesystem_class
  20. from fsspec.utils import (
  21. _unstrip_protocol,
  22. build_name_function,
  23. infer_compression,
  24. stringify_path,
  25. )
  26. logger = logging.getLogger("fsspec")
  27. class OpenFile:
  28. """
  29. File-like object to be used in a context
  30. Can layer (buffered) text-mode and compression over any file-system, which
  31. are typically binary-only.
  32. These instances are safe to serialize, as the low-level file object
  33. is not created until invoked using ``with``.
  34. Parameters
  35. ----------
  36. fs: FileSystem
  37. The file system to use for opening the file. Should be a subclass or duck-type
  38. with ``fsspec.spec.AbstractFileSystem``
  39. path: str
  40. Location to open
  41. mode: str like 'rb', optional
  42. Mode of the opened file
  43. compression: str or None, optional
  44. Compression to apply
  45. encoding: str or None, optional
  46. The encoding to use if opened in text mode.
  47. errors: str or None, optional
  48. How to handle encoding errors if opened in text mode.
  49. newline: None or str
  50. Passed to TextIOWrapper in text mode, how to handle line endings.
  51. autoopen: bool
  52. If True, calls open() immediately. Mostly used by pickle
  53. pos: int
  54. If given and autoopen is True, seek to this location immediately
  55. """
  56. def __init__(
  57. self,
  58. fs,
  59. path,
  60. mode="rb",
  61. compression=None,
  62. encoding=None,
  63. errors=None,
  64. newline=None,
  65. ):
  66. self.fs = fs
  67. self.path = path
  68. self.mode = mode
  69. self.compression = get_compression(path, compression)
  70. self.encoding = encoding
  71. self.errors = errors
  72. self.newline = newline
  73. self.fobjects = []
  74. def __reduce__(self):
  75. return (
  76. OpenFile,
  77. (
  78. self.fs,
  79. self.path,
  80. self.mode,
  81. self.compression,
  82. self.encoding,
  83. self.errors,
  84. self.newline,
  85. ),
  86. )
  87. def __repr__(self):
  88. return f"<OpenFile '{self.path}'>"
  89. def __enter__(self):
  90. mode = self.mode.replace("t", "").replace("b", "") + "b"
  91. try:
  92. f = self.fs.open(self.path, mode=mode)
  93. except FileNotFoundError as e:
  94. if has_magic(self.path):
  95. raise FileNotFoundError(
  96. "%s not found. The URL contains glob characters: you maybe needed\n"
  97. "to pass expand=True in fsspec.open() or the storage_options of \n"
  98. "your library. You can also set the config value 'open_expand'\n"
  99. "before import, or fsspec.core.DEFAULT_EXPAND at runtime, to True.",
  100. self.path,
  101. ) from e
  102. raise
  103. self.fobjects = [f]
  104. if self.compression is not None:
  105. compress = compr[self.compression]
  106. f = compress(f, mode=mode[0])
  107. self.fobjects.append(f)
  108. if "b" not in self.mode:
  109. # assume, for example, that 'r' is equivalent to 'rt' as in builtin
  110. f = PickleableTextIOWrapper(
  111. f, encoding=self.encoding, errors=self.errors, newline=self.newline
  112. )
  113. self.fobjects.append(f)
  114. return self.fobjects[-1]
  115. def __exit__(self, *args):
  116. self.close()
  117. @property
  118. def full_name(self):
  119. return _unstrip_protocol(self.path, self.fs)
  120. def open(self):
  121. """Materialise this as a real open file without context
  122. The OpenFile object should be explicitly closed to avoid enclosed file
  123. instances persisting. You must, therefore, keep a reference to the OpenFile
  124. during the life of the file-like it generates.
  125. """
  126. return self.__enter__()
  127. def close(self):
  128. """Close all encapsulated file objects"""
  129. for f in reversed(self.fobjects):
  130. if "r" not in self.mode and not f.closed:
  131. f.flush()
  132. f.close()
  133. self.fobjects.clear()
  134. class OpenFiles(list):
  135. """List of OpenFile instances
  136. Can be used in a single context, which opens and closes all of the
  137. contained files. Normal list access to get the elements works as
  138. normal.
  139. A special case is made for caching filesystems - the files will
  140. be down/uploaded together at the start or end of the context, and
  141. this may happen concurrently, if the target filesystem supports it.
  142. """
  143. def __init__(self, *args, mode="rb", fs=None):
  144. self.mode = mode
  145. self.fs = fs
  146. self.files = []
  147. super().__init__(*args)
  148. def __enter__(self):
  149. if self.fs is None:
  150. raise ValueError("Context has already been used")
  151. fs = self.fs
  152. while True:
  153. if hasattr(fs, "open_many"):
  154. # check for concurrent cache download; or set up for upload
  155. self.files = fs.open_many(self)
  156. return self.files
  157. if hasattr(fs, "fs") and fs.fs is not None:
  158. fs = fs.fs
  159. else:
  160. break
  161. return [s.__enter__() for s in self]
  162. def __exit__(self, *args):
  163. fs = self.fs
  164. [s.__exit__(*args) for s in self]
  165. if "r" not in self.mode:
  166. while True:
  167. if hasattr(fs, "open_many"):
  168. # check for concurrent cache upload
  169. fs.commit_many(self.files)
  170. return
  171. if hasattr(fs, "fs") and fs.fs is not None:
  172. fs = fs.fs
  173. else:
  174. break
  175. def __getitem__(self, item):
  176. out = super().__getitem__(item)
  177. if isinstance(item, slice):
  178. return OpenFiles(out, mode=self.mode, fs=self.fs)
  179. return out
  180. def __repr__(self):
  181. return f"<List of {len(self)} OpenFile instances>"
  182. def open_files(
  183. urlpath,
  184. mode="rb",
  185. compression=None,
  186. encoding="utf8",
  187. errors=None,
  188. name_function=None,
  189. num=1,
  190. protocol=None,
  191. newline=None,
  192. auto_mkdir=True,
  193. expand=True,
  194. **kwargs,
  195. ):
  196. """Given a path or paths, return a list of ``OpenFile`` objects.
  197. For writing, a str path must contain the "*" character, which will be filled
  198. in by increasing numbers, e.g., "part*" -> "part1", "part2" if num=2.
  199. For either reading or writing, can instead provide explicit list of paths.
  200. Parameters
  201. ----------
  202. urlpath: string or list
  203. Absolute or relative filepath(s). Prefix with a protocol like ``s3://``
  204. to read from alternative filesystems. To read from multiple files you
  205. can pass a globstring or a list of paths, with the caveat that they
  206. must all have the same protocol.
  207. mode: 'rb', 'wt', etc.
  208. compression: string or None
  209. If given, open file using compression codec. Can either be a compression
  210. name (a key in ``fsspec.compression.compr``) or "infer" to guess the
  211. compression from the filename suffix.
  212. encoding: str
  213. For text mode only
  214. errors: None or str
  215. Passed to TextIOWrapper in text mode
  216. name_function: function or None
  217. if opening a set of files for writing, those files do not yet exist,
  218. so we need to generate their names by formatting the urlpath for
  219. each sequence number
  220. num: int [1]
  221. if writing mode, number of files we expect to create (passed to
  222. name+function)
  223. protocol: str or None
  224. If given, overrides the protocol found in the URL.
  225. newline: bytes or None
  226. Used for line terminator in text mode. If None, uses system default;
  227. if blank, uses no translation.
  228. auto_mkdir: bool (True)
  229. If in write mode, this will ensure the target directory exists before
  230. writing, by calling ``fs.mkdirs(exist_ok=True)``.
  231. expand: bool
  232. **kwargs: dict
  233. Extra options that make sense to a particular storage connection, e.g.
  234. host, port, username, password, etc.
  235. Examples
  236. --------
  237. >>> files = open_files('2015-*-*.csv') # doctest: +SKIP
  238. >>> files = open_files(
  239. ... 's3://bucket/2015-*-*.csv.gz', compression='gzip'
  240. ... ) # doctest: +SKIP
  241. Returns
  242. -------
  243. An ``OpenFiles`` instance, which is a list of ``OpenFile`` objects that can
  244. be used as a single context
  245. Notes
  246. -----
  247. For a full list of the available protocols and the implementations that
  248. they map across to see the latest online documentation:
  249. - For implementations built into ``fsspec`` see
  250. https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
  251. - For implementations in separate packages see
  252. https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
  253. """
  254. fs, fs_token, paths = get_fs_token_paths(
  255. urlpath,
  256. mode,
  257. num=num,
  258. name_function=name_function,
  259. storage_options=kwargs,
  260. protocol=protocol,
  261. expand=expand,
  262. )
  263. if fs.protocol == "file":
  264. fs.auto_mkdir = auto_mkdir
  265. elif "r" not in mode and auto_mkdir:
  266. parents = {fs._parent(path) for path in paths}
  267. for parent in parents:
  268. try:
  269. fs.makedirs(parent, exist_ok=True)
  270. except PermissionError:
  271. pass
  272. return OpenFiles(
  273. [
  274. OpenFile(
  275. fs,
  276. path,
  277. mode=mode,
  278. compression=compression,
  279. encoding=encoding,
  280. errors=errors,
  281. newline=newline,
  282. )
  283. for path in paths
  284. ],
  285. mode=mode,
  286. fs=fs,
  287. )
  288. def _un_chain(path, kwargs):
  289. # Avoid a circular import
  290. from fsspec.implementations.cached import CachingFileSystem
  291. if "::" in path:
  292. x = re.compile(".*[^a-z]+.*") # test for non protocol-like single word
  293. bits = []
  294. for p in path.split("::"):
  295. if "://" in p or x.match(p):
  296. bits.append(p)
  297. else:
  298. bits.append(p + "://")
  299. else:
  300. bits = [path]
  301. # [[url, protocol, kwargs], ...]
  302. out = []
  303. previous_bit = None
  304. kwargs = kwargs.copy()
  305. for bit in reversed(bits):
  306. protocol = kwargs.pop("protocol", None) or split_protocol(bit)[0] or "file"
  307. cls = get_filesystem_class(protocol)
  308. extra_kwargs = cls._get_kwargs_from_urls(bit)
  309. kws = kwargs.pop(protocol, {})
  310. if bit is bits[0]:
  311. kws.update(kwargs)
  312. kw = dict(
  313. **{k: v for k, v in extra_kwargs.items() if k not in kws or v != kws[k]},
  314. **kws,
  315. )
  316. bit = cls._strip_protocol(bit)
  317. if "target_protocol" not in kw and issubclass(cls, CachingFileSystem):
  318. bit = previous_bit
  319. out.append((bit, protocol, kw))
  320. previous_bit = bit
  321. out.reverse()
  322. return out
  323. def url_to_fs(url, **kwargs):
  324. """
  325. Turn fully-qualified and potentially chained URL into filesystem instance
  326. Parameters
  327. ----------
  328. url : str
  329. The fsspec-compatible URL
  330. **kwargs: dict
  331. Extra options that make sense to a particular storage connection, e.g.
  332. host, port, username, password, etc.
  333. Returns
  334. -------
  335. filesystem : FileSystem
  336. The new filesystem discovered from ``url`` and created with
  337. ``**kwargs``.
  338. urlpath : str
  339. The file-systems-specific URL for ``url``.
  340. """
  341. url = stringify_path(url)
  342. # non-FS arguments that appear in fsspec.open()
  343. # inspect could keep this in sync with open()'s signature
  344. known_kwargs = {
  345. "compression",
  346. "encoding",
  347. "errors",
  348. "expand",
  349. "mode",
  350. "name_function",
  351. "newline",
  352. "num",
  353. }
  354. kwargs = {k: v for k, v in kwargs.items() if k not in known_kwargs}
  355. chain = _un_chain(url, kwargs)
  356. inkwargs = {}
  357. # Reverse iterate the chain, creating a nested target_* structure
  358. for i, ch in enumerate(reversed(chain)):
  359. urls, protocol, kw = ch
  360. if i == len(chain) - 1:
  361. inkwargs = dict(**kw, **inkwargs)
  362. continue
  363. inkwargs["target_options"] = dict(**kw, **inkwargs)
  364. inkwargs["target_protocol"] = protocol
  365. inkwargs["fo"] = urls
  366. urlpath, protocol, _ = chain[0]
  367. fs = filesystem(protocol, **inkwargs)
  368. return fs, urlpath
  369. DEFAULT_EXPAND = conf.get("open_expand", False)
  370. def open(
  371. urlpath,
  372. mode="rb",
  373. compression=None,
  374. encoding="utf8",
  375. errors=None,
  376. protocol=None,
  377. newline=None,
  378. expand=None,
  379. **kwargs,
  380. ):
  381. """Given a path or paths, return one ``OpenFile`` object.
  382. Parameters
  383. ----------
  384. urlpath: string or list
  385. Absolute or relative filepath. Prefix with a protocol like ``s3://``
  386. to read from alternative filesystems. Should not include glob
  387. character(s).
  388. mode: 'rb', 'wt', etc.
  389. compression: string or None
  390. If given, open file using compression codec. Can either be a compression
  391. name (a key in ``fsspec.compression.compr``) or "infer" to guess the
  392. compression from the filename suffix.
  393. encoding: str
  394. For text mode only
  395. errors: None or str
  396. Passed to TextIOWrapper in text mode
  397. protocol: str or None
  398. If given, overrides the protocol found in the URL.
  399. newline: bytes or None
  400. Used for line terminator in text mode. If None, uses system default;
  401. if blank, uses no translation.
  402. expand: bool or None
  403. Whether to regard file paths containing special glob characters as needing
  404. expansion (finding the first match) or absolute. Setting False allows using
  405. paths which do embed such characters. If None (default), this argument
  406. takes its value from the DEFAULT_EXPAND module variable, which takes
  407. its initial value from the "open_expand" config value at startup, which will
  408. be False if not set.
  409. **kwargs: dict
  410. Extra options that make sense to a particular storage connection, e.g.
  411. host, port, username, password, etc.
  412. Examples
  413. --------
  414. >>> openfile = open('2015-01-01.csv') # doctest: +SKIP
  415. >>> openfile = open(
  416. ... 's3://bucket/2015-01-01.csv.gz', compression='gzip'
  417. ... ) # doctest: +SKIP
  418. >>> with openfile as f:
  419. ... df = pd.read_csv(f) # doctest: +SKIP
  420. ...
  421. Returns
  422. -------
  423. ``OpenFile`` object.
  424. Notes
  425. -----
  426. For a full list of the available protocols and the implementations that
  427. they map across to see the latest online documentation:
  428. - For implementations built into ``fsspec`` see
  429. https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
  430. - For implementations in separate packages see
  431. https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
  432. """
  433. expand = DEFAULT_EXPAND if expand is None else expand
  434. out = open_files(
  435. urlpath=[urlpath],
  436. mode=mode,
  437. compression=compression,
  438. encoding=encoding,
  439. errors=errors,
  440. protocol=protocol,
  441. newline=newline,
  442. expand=expand,
  443. **kwargs,
  444. )
  445. if not out:
  446. raise FileNotFoundError(urlpath)
  447. return out[0]
  448. def open_local(
  449. url: str | list[str] | Path | list[Path],
  450. mode: str = "rb",
  451. **storage_options: dict,
  452. ) -> str | list[str]:
  453. """Open file(s) which can be resolved to local
  454. For files which either are local, or get downloaded upon open
  455. (e.g., by file caching)
  456. Parameters
  457. ----------
  458. url: str or list(str)
  459. mode: str
  460. Must be read mode
  461. storage_options:
  462. passed on to FS for or used by open_files (e.g., compression)
  463. """
  464. if "r" not in mode:
  465. raise ValueError("Can only ensure local files when reading")
  466. of = open_files(url, mode=mode, **storage_options)
  467. if not getattr(of[0].fs, "local_file", False):
  468. raise ValueError(
  469. "open_local can only be used on a filesystem which"
  470. " has attribute local_file=True"
  471. )
  472. with of as files:
  473. paths = [f.name for f in files]
  474. if (isinstance(url, str) and not has_magic(url)) or isinstance(url, Path):
  475. return paths[0]
  476. return paths
  477. def get_compression(urlpath, compression):
  478. if compression == "infer":
  479. compression = infer_compression(urlpath)
  480. if compression is not None and compression not in compr:
  481. raise ValueError(f"Compression type {compression} not supported")
  482. return compression
  483. def split_protocol(urlpath):
  484. """Return protocol, path pair"""
  485. urlpath = stringify_path(urlpath)
  486. if "://" in urlpath:
  487. protocol, path = urlpath.split("://", 1)
  488. if len(protocol) > 1:
  489. # excludes Windows paths
  490. return protocol, path
  491. if urlpath.startswith("data:"):
  492. return urlpath.split(":", 1)
  493. return None, urlpath
  494. def strip_protocol(urlpath):
  495. """Return only path part of full URL, according to appropriate backend"""
  496. protocol, _ = split_protocol(urlpath)
  497. cls = get_filesystem_class(protocol)
  498. return cls._strip_protocol(urlpath)
  499. def expand_paths_if_needed(paths, mode, num, fs, name_function):
  500. """Expand paths if they have a ``*`` in them (write mode) or any of ``*?[]``
  501. in them (read mode).
  502. :param paths: list of paths
  503. mode: str
  504. Mode in which to open files.
  505. num: int
  506. If opening in writing mode, number of files we expect to create.
  507. fs: filesystem object
  508. name_function: callable
  509. If opening in writing mode, this callable is used to generate path
  510. names. Names are generated for each partition by
  511. ``urlpath.replace('*', name_function(partition_index))``.
  512. :return: list of paths
  513. """
  514. expanded_paths = []
  515. paths = list(paths)
  516. if "w" in mode: # read mode
  517. if sum(1 for p in paths if "*" in p) > 1:
  518. raise ValueError(
  519. "When writing data, only one filename mask can be specified."
  520. )
  521. num = max(num, len(paths))
  522. for curr_path in paths:
  523. if "*" in curr_path:
  524. # expand using name_function
  525. expanded_paths.extend(_expand_paths(curr_path, name_function, num))
  526. else:
  527. expanded_paths.append(curr_path)
  528. # if we generated more paths that asked for, trim the list
  529. if len(expanded_paths) > num:
  530. expanded_paths = expanded_paths[:num]
  531. else: # read mode
  532. for curr_path in paths:
  533. if has_magic(curr_path):
  534. # expand using glob
  535. expanded_paths.extend(fs.glob(curr_path))
  536. else:
  537. expanded_paths.append(curr_path)
  538. return expanded_paths
  539. def get_fs_token_paths(
  540. urlpath,
  541. mode="rb",
  542. num=1,
  543. name_function=None,
  544. storage_options=None,
  545. protocol=None,
  546. expand=True,
  547. ):
  548. """Filesystem, deterministic token, and paths from a urlpath and options.
  549. Parameters
  550. ----------
  551. urlpath: string or iterable
  552. Absolute or relative filepath, URL (may include protocols like
  553. ``s3://``), or globstring pointing to data.
  554. mode: str, optional
  555. Mode in which to open files.
  556. num: int, optional
  557. If opening in writing mode, number of files we expect to create.
  558. name_function: callable, optional
  559. If opening in writing mode, this callable is used to generate path
  560. names. Names are generated for each partition by
  561. ``urlpath.replace('*', name_function(partition_index))``.
  562. storage_options: dict, optional
  563. Additional keywords to pass to the filesystem class.
  564. protocol: str or None
  565. To override the protocol specifier in the URL
  566. expand: bool
  567. Expand string paths for writing, assuming the path is a directory
  568. """
  569. if isinstance(urlpath, (list, tuple, set)):
  570. if not urlpath:
  571. raise ValueError("empty urlpath sequence")
  572. urlpath0 = stringify_path(next(iter(urlpath)))
  573. else:
  574. urlpath0 = stringify_path(urlpath)
  575. storage_options = storage_options or {}
  576. if protocol:
  577. storage_options["protocol"] = protocol
  578. chain = _un_chain(urlpath0, storage_options or {})
  579. inkwargs = {}
  580. # Reverse iterate the chain, creating a nested target_* structure
  581. for i, ch in enumerate(reversed(chain)):
  582. urls, nested_protocol, kw = ch
  583. if i == len(chain) - 1:
  584. inkwargs = dict(**kw, **inkwargs)
  585. continue
  586. inkwargs["target_options"] = dict(**kw, **inkwargs)
  587. inkwargs["target_protocol"] = nested_protocol
  588. inkwargs["fo"] = urls
  589. paths, protocol, _ = chain[0]
  590. fs = filesystem(protocol, **inkwargs)
  591. if isinstance(urlpath, (list, tuple, set)):
  592. pchains = [
  593. _un_chain(stringify_path(u), storage_options or {})[0] for u in urlpath
  594. ]
  595. if len({pc[1] for pc in pchains}) > 1:
  596. raise ValueError("Protocol mismatch getting fs from %s", urlpath)
  597. paths = [pc[0] for pc in pchains]
  598. else:
  599. paths = fs._strip_protocol(paths)
  600. if isinstance(paths, (list, tuple, set)):
  601. if expand:
  602. paths = expand_paths_if_needed(paths, mode, num, fs, name_function)
  603. elif not isinstance(paths, list):
  604. paths = list(paths)
  605. else:
  606. if ("w" in mode or "x" in mode) and expand:
  607. paths = _expand_paths(paths, name_function, num)
  608. elif "*" in paths:
  609. paths = [f for f in sorted(fs.glob(paths)) if not fs.isdir(f)]
  610. else:
  611. paths = [paths]
  612. return fs, fs._fs_token, paths
  613. def _expand_paths(path, name_function, num):
  614. if isinstance(path, str):
  615. if path.count("*") > 1:
  616. raise ValueError("Output path spec must contain exactly one '*'.")
  617. elif "*" not in path:
  618. path = os.path.join(path, "*.part")
  619. if name_function is None:
  620. name_function = build_name_function(num - 1)
  621. paths = [path.replace("*", name_function(i)) for i in range(num)]
  622. if paths != sorted(paths):
  623. logger.warning(
  624. "In order to preserve order between partitions"
  625. " paths created with ``name_function`` should "
  626. "sort to partition order"
  627. )
  628. elif isinstance(path, (tuple, list)):
  629. assert len(path) == num
  630. paths = list(path)
  631. else:
  632. raise ValueError(
  633. "Path should be either\n"
  634. "1. A list of paths: ['foo.json', 'bar.json', ...]\n"
  635. "2. A directory: 'foo/\n"
  636. "3. A path with a '*' in it: 'foo.*.json'"
  637. )
  638. return paths
  639. class PickleableTextIOWrapper(io.TextIOWrapper):
  640. """TextIOWrapper cannot be pickled. This solves it.
  641. Requires that ``buffer`` be pickleable, which all instances of
  642. AbstractBufferedFile are.
  643. """
  644. def __init__(
  645. self,
  646. buffer,
  647. encoding=None,
  648. errors=None,
  649. newline=None,
  650. line_buffering=False,
  651. write_through=False,
  652. ):
  653. self.args = buffer, encoding, errors, newline, line_buffering, write_through
  654. super().__init__(*self.args)
  655. def __reduce__(self):
  656. return PickleableTextIOWrapper, self.args