Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions python/diffuse/_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

import atexit
import importlib
import itertools
import os
import re
import shutil
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
16 changes: 16 additions & 0 deletions tests/python/test_diffuse_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Loading