Skip to content

Commit

Permalink
Delete processing_directory if created but empty after processing
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas Fish committed Nov 6, 2024
1 parent 4cd9132 commit 0e56ec5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 17 deletions.
22 changes: 22 additions & 0 deletions src/sim_recon/files/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,3 +235,25 @@ def __init__(
ignore_cleanup_errors=ignore_cleanup_errors,
delete=delete,
)


@contextmanager
def delete_directory_if_empty(
path: str | PathLike[str] | None,
) -> Generator[None, None, None]:
if path is None:
yield None
return
try_cleanup = not os.path.isdir(path)
try:
yield None
finally:
if try_cleanup and os.path.isdir(path):
with os.scandir(path) as it:
directory_empty = not any(it) # False if any entries found
if directory_empty:
logger.info(
"Removing empty directory '%s'",
path,
)
os.rmdir(path)
21 changes: 4 additions & 17 deletions src/sim_recon/recon.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
redirect_output_to,
create_output_path,
combine_text_files,
delete_directory_if_empty,
NamedTemporaryDirectory,
)
from .files.config import create_wavelength_config
Expand Down Expand Up @@ -389,6 +390,7 @@ def run_reconstructions(
maxtasksperchild=1,
) as pool,
logging_redirect(),
delete_directory_if_empty(processing_directory),
):
for sim_data_path in progress_wrapper(
sim_data_paths, desc="SIM data files", unit="file"
Expand Down Expand Up @@ -417,9 +419,8 @@ def run_reconstructions(
) as proc_dir:
proc_dir = Path(proc_dir)

# These processing files are cleaned up by TemporaryDirectory
# As single-wavelength files will be used directly and we don't
# want to delete real input files!
# These processing files are cleaned up by
# NamedTemporaryDirectory if cleanup == True
processing_info_dict = _prepare_files(
sim_data_path,
proc_dir,
Expand Down Expand Up @@ -516,20 +517,6 @@ def run_reconstructions(
"Reconstruction log file created at '%s'", log_path
)

if cleanup:
for processing_info in processing_info_dict.values():
try:
if processing_info.output_path.is_file():
logger.debug(
"Removing %s", processing_info.output_path
)
os.remove(processing_info.output_path)
except Exception:
logger.error(
"Failed to remove %s",
processing_info.output_path,
exc_info=True,
)
except ConfigException as e:
logger.error("Unable to process %s: %s", sim_data_path, e)
except PySimReconException as e:
Expand Down

0 comments on commit 0e56ec5

Please sign in to comment.