Skip to content

Commit daa7431

Browse files
committed
On LibraryManager destruction, delete any temporary files generated.
1 parent 7981530 commit daa7431

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

src/axelrod_fortran/player.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ def __init__(self, shared_library_name, verbose=False):
4848
# Generate a random prefix for tempfile generation
4949
self.prefix = str(uuid.uuid4())
5050
self.library_path = self.find_shared_library(shared_library_name)
51+
self.filenames = []
5152

5253
def find_shared_library(self, shared_library_name):
5354
## This finds only the relative path to the library, unfortunately.
@@ -57,6 +58,7 @@ def find_shared_library(self, shared_library_name):
5758
return "/usr/lib/libstrategies.so"
5859

5960
def load_dll_copy(self):
61+
"""Load a new copy of the shared library."""
6062
# Copy the library file to a new location so we can load the copy.
6163
temp_directory = tempfile.gettempdir()
6264
copy_number = len(self.library_copies)
@@ -70,6 +72,7 @@ def load_dll_copy(self):
7072
if self.verbose:
7173
print("Loading {}".format(new_filename))
7274
shutil.copy2(self.library_path, new_filename)
75+
self.filenames.append(new_filename)
7376
shared_library = cdll.LoadLibrary(new_filename)
7477
self.library_copies.append(shared_library)
7578

@@ -91,6 +94,8 @@ def next_player_index(self, name):
9194
raise ValueError("We shouldn't be here.")
9295

9396
def load_library_for_player(self, name):
97+
"""For a given player return a copy of the shared library for use
98+
in a Player class, along with an index for later releasing."""
9499
index = self.next_player_index(name)
95100
self.player_indices[name].add(index)
96101
if self.verbose:
@@ -104,6 +109,12 @@ def release(self, name, index):
104109
print("releasing {}".format(index))
105110
self.player_next[name].add(index)
106111

112+
def __del__(self):
113+
"""Cleanup temp files on object deletion."""
114+
for filename in self.filenames:
115+
if os.path.exists(filename):
116+
os.remove(filename)
117+
107118

108119
class Player(axl.Player):
109120

@@ -121,13 +132,14 @@ def __init__(self, original_name,
121132
game: axelrod.Game
122133
A instance of an axelrod Game
123134
"""
135+
super().__init__()
124136
if not Player.library_manager:
125137
Player.library_manager = LibraryManager(shared_library_name)
126-
super().__init__()
127138
self.index, self.shared_library = \
128139
self.library_manager.load_library_for_player(original_name)
129140
self.original_name = original_name
130141
self.original_function = self.original_name
142+
131143
is_stochastic = characteristics[self.original_name]['stochastic']
132144
if is_stochastic is not None:
133145
self.classifier['stochastic'] = is_stochastic

0 commit comments

Comments
 (0)