diff --git a/python/diffuse/_session.py b/python/diffuse/_session.py index 5dff32b2..4eed4d04 100644 --- a/python/diffuse/_session.py +++ b/python/diffuse/_session.py @@ -22,7 +22,6 @@ import atexit import importlib -import itertools import os import re import shutil @@ -115,7 +114,6 @@ def __init__(self, echo: bool | None = None): self.echo = bool(os.environ.get("DIFFUSE_ECHO")) if echo is None else echo self.last_output = "" self._s = _import_suite_python() - self._count = itertools.count() self._workdir = Path(tempfile.mkdtemp(prefix="diffuse_")) atexit.register(shutil.rmtree, self._workdir, ignore_errors=True) self.current_crystal = None # the Crystal now held by DISCUS @@ -145,7 +143,12 @@ def run(self, commands: str, cwd: str | os.PathLike | None = None) -> str: Raises MacroError if a command error stopped the macro. """ cwd = Path(cwd or self._workdir).resolve() - driver = self._workdir / f"_driver_{next(self._count)}.mac" + # One driver file per session, overwritten on every call. DISCUS keeps + # macros in memory by file name, but empties that store when a + # top-level macro ends (also after an error), so the new text is + # always read. The scratch folder stays at a few files however many + # calls a session makes. + driver = self._workdir / "_driver.mac" driver.write_text( f"cd {cwd}\n" f"{FLAG} = 0\n" diff --git a/tests/python/test_diffuse_api.py b/tests/python/test_diffuse_api.py index f9753feb..f3ca1cc8 100644 --- a/tests/python/test_diffuse_api.py +++ b/tests/python/test_diffuse_api.py @@ -75,6 +75,22 @@ def test_working_directory_kept(dc, tmp_path, monkeypatch): assert Path.cwd() == tmp_path +def test_scratch_folder_does_not_grow(dc): + """Every call reuses the same driver macro; the scratch folder stays small.""" + cr = dc.read_structure(ANATASE) + dc.powder(cr, qmax=3.0) + before = sorted(p.name for p in dc.session().workdir.rglob("*")) + for value in range(20): + dc.run_macro(f"r[1] = {value}") + assert dc.session().value("r[1]") == value # new text every time + with pytest.raises(dc.MacroError): + dc.run_macro("discus\n no_such_command\nexit") + dc.run_macro("r[1] = 99") # and after an error + assert dc.session().value("r[1]") == 99 + dc.powder(cr, qmax=3.0) + assert sorted(p.name for p in dc.session().workdir.rglob("*")) == before + + def test_macro_error_message(dc): with pytest.raises(dc.MacroError) as info: dc.run_macro("discus\n no_such_command 1\nexit")