gstlal 1.13.0
Loading...
Searching...
No Matches
laltools.py
1"""This module contains miscellaneous utilities for working with LAL data structures and api
2
3"""
4import os
5import pathlib
6import tempfile
7from typing import Union, Iterable, Optional
8
9from lal.utils import CacheEntry
10
11
12def create_cache(entries: Iterable[Union[str, pathlib.Path, CacheEntry]], cache_path: Optional[Union[str, pathlib.Path]] = None,
13 use_os_tmpdir: bool = True) -> pathlib.Path:
14 """Create a LAL cache file from an iterable of entries
15
16 Args:
17 entries:
18 Iterable of either str, Path, or CacheEntry. If str or Path, a CacheEntry will be created using CacheEntry.from_T050017
19 cache_path:
20 use_os_tmpdir:
21 bool, if True use 'TMPDIR' env variable else create a tmp directory using tempfile.TemporaryDirectory. Only applies if
22 cache_path argument is None.
23
24 Returns:
25 pathlib.Path, the path to the cache file
26 """
27 # Coerce entry types
28 cache_entries = []
29 for entry in entries:
30 if isinstance(entry, str):
31 entry = pathlib.Path(entry)
32 if isinstance(entry, pathlib.Path):
33 entry = CacheEntry.from_T050017(url=entry.as_uri())
34 cache_entries.append(entry)
35
36 # Set cache path
37 if cache_path is None:
38 tmpdir = os.getenv('TMPDIR') if use_os_tmpdir else tempfile.TemporaryDirectory()
39 cache_path = tempfile.NamedTemporaryFile(suffix='.cache', dir=tmpdir).name
40 if isinstance(cache_path, str):
41 cache_path = pathlib.Path(cache_path)
42
43 # Write cache file
44 with open(cache_path.as_posix(), 'w') as fid:
45 for entry in cache_entries:
46 fid.write(str(entry))
47
48 return cache_path
pathlib.Path create_cache(Iterable[Union[str, pathlib.Path, CacheEntry]] entries, Optional[Union[str, pathlib.Path]] cache_path=None, bool use_os_tmpdir=True)
Definition laltools.py:13