|
20 | 20 | from torch.distributed.fsdp import StateDictType |
21 | 21 |
|
22 | 22 |
|
23 | | -def get_latest(targdir, qualifier=lambda x: True): |
24 | | - """Fetch the latest file or folder written to target directory, subject to name passing the qualifier fn. |
25 | | - If directory is empty or nonexistent or no items qualify, return None.""" |
| 23 | +def get_latest(targdir, qualifier=lambda x: True, key=os.path.getctime): |
| 24 | + """ |
| 25 | + Fetch the full path of the latest file or folder written to target directory, |
| 26 | + subject to name passing the qualifier fn. |
| 27 | + Optional key fn can be used for custom sorting. |
| 28 | + Both functions take full path arguments. |
| 29 | + If directory is empty or nonexistent or no items qualify, return None. |
| 30 | + """ |
26 | 31 | if os.path.exists(targdir) and len(os.listdir(targdir)) > 0: |
27 | 32 | latest = max( |
28 | 33 | [ |
29 | 34 | os.path.join(targdir, x) |
30 | 35 | for x in os.listdir(targdir) |
31 | 36 | if qualifier(os.path.join(targdir, x)) |
32 | 37 | ], |
33 | | - key=lambda path: int(path.split("/")[-1].split("_")[1]), |
| 38 | + key=key, |
34 | 39 | ) |
35 | | - return os.path.join(targdir, latest) |
| 40 | + return latest |
36 | 41 | return None |
37 | 42 |
|
38 | 43 |
|
39 | | -def get_oldest(targdir, qualifier=lambda x: True): |
40 | | - """Fetch the oldest file or folder written to target directory, subject to name passing the qualifier fn. |
41 | | - If directory is empty or nonexistent or no items qualify, return None.""" |
| 44 | +def get_oldest(targdir, qualifier=lambda x: True, key=os.path.getctime): |
| 45 | + """ |
| 46 | + Fetch the full path of the oldest file or folder written to target directory, |
| 47 | + subject to name passing the qualifier fn. |
| 48 | + Optional key fn can be used for custom sorting. |
| 49 | + Both functions take full path arguments. |
| 50 | + If directory is empty or nonexistent or no items qualify, return None. |
| 51 | + """ |
42 | 52 | if os.path.exists(targdir) and len(os.listdir(targdir)) > 0: |
43 | 53 | oldest = min( |
44 | 54 | [ |
45 | 55 | os.path.join(targdir, x) |
46 | 56 | for x in os.listdir(targdir) |
47 | 57 | if qualifier(os.path.join(targdir, x)) |
48 | 58 | ], |
49 | | - key=os.path.getctime, |
| 59 | + key=key, |
50 | 60 | ) |
51 | | - return os.path.join(targdir, oldest) |
| 61 | + return oldest |
52 | 62 | return None |
53 | 63 |
|
54 | 64 |
|
@@ -118,7 +128,7 @@ def _cleanup(self): |
118 | 128 | ckp_to_remove = Path( |
119 | 129 | get_oldest(self.ckp_path, qualifier=lambda x: "tmp" in x) |
120 | 130 | ) |
121 | | - if os.path.is_file(ckp_to_remove): |
| 131 | + if os.path.isfile(ckp_to_remove): |
122 | 132 | ckp_to_remove.unlink() |
123 | 133 | else: |
124 | 134 | shutil.rmtree(ckp_to_remove) |
|
0 commit comments