Skip to content

Commit

Permalink
feat: using tempfile module more extensively.
Browse files Browse the repository at this point in the history
  • Loading branch information
germa89 committed Jul 9, 2024
1 parent e37417e commit a7a69cb
Show file tree
Hide file tree
Showing 6 changed files with 25 additions and 38 deletions.
5 changes: 1 addition & 4 deletions src/ansys/mapdl/core/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import re
import socket
import subprocess
import tempfile
import threading
import time
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
Expand Down Expand Up @@ -71,7 +70,6 @@
check_valid_ip,
check_valid_port,
create_temp_dir,
random_string,
threaded,
)

Expand Down Expand Up @@ -1681,8 +1679,7 @@ def launch_mapdl(
# verify run location
if run_location is None:
LOG.debug("Using default run location.")
temp_dir = tempfile.gettempdir()
run_location = os.path.join(temp_dir, "ansys_%s" % random_string(10))
run_location = create_temp_dir()
if not os.path.isdir(run_location):
try:
os.mkdir(run_location)
Expand Down
6 changes: 4 additions & 2 deletions src/ansys/mapdl/core/mapdl_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1879,8 +1879,10 @@ def _flush_stored(self):
"""
self._log.debug("Flushing stored commands")
rnd_str = random_string()
tmp_out = os.path.join(tempfile.gettempdir(), f"tmp_{rnd_str}.out")
tmp_out = tempfile.NamedTemporaryFile(
prefix="tmp_", suffix=".out", delete=False
).name

self._stored_commands.insert(0, "/OUTPUT, f'{tmp_out}'")
self._stored_commands.append("/OUTPUT")
commands = "\n".join(self._stored_commands)
Expand Down
19 changes: 11 additions & 8 deletions src/ansys/mapdl/core/mapdl_extended.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@
allow_iterables_vmin,
allow_pickable_entities,
load_file,
random_string,
supress_logging,
)
from ansys.mapdl.core.theme import get_ansys_colors
Expand Down Expand Up @@ -2156,13 +2155,16 @@ def load_table(self, name, array, var1="", var2="", var3="", csysid=""):
if array.shape[1] > 2:
array = np.vstack((array[0], array))

base_name = random_string() + ".txt"
filename = os.path.join(tempfile.gettempdir(), base_name)
filename = tempfile.NamedTemporaryFile(
prefix="pymapdl_load_table_", suffix=".txt", delete=False
).name
np.savetxt(filename, array, header="File generated by PyMAPDL:load_table")
self._log.info(f"Generated temporary file to store table: {filename}")

if not self._local:
self.upload(filename, progress_bar=False)
filename = base_name
filename = os.path.basename(filename)

# skip the first line its a header we wrote in np.savetxt
self.tread(name, filename, nskip=1, mute=True)

Expand Down Expand Up @@ -2225,20 +2227,21 @@ def load_array(self, name, array):

self.dim(name, "ARRAY", imax=imax, jmax=jmax, kmax="")

base_name = random_string() + ".txt"
filename = os.path.join(tempfile.gettempdir(), base_name)
self._log.info(f"Generating file for table in {filename}")
filename = tempfile.NamedTemporaryFile(
prefix="pymapdl_load_array_", suffix=".txt", delete=False
).name
np.savetxt(
filename,
array,
delimiter=",",
header="File generated by PyMAPDL:load_array",
fmt="%24.18e",
)
self._log.info(f"Generated temporary file to store array: {filename}")

if not self._local:
self.upload(filename, progress_bar=False)
filename = base_name
filename = os.path.basename(filename)

with self.non_interactive:
label = "jik"
Expand Down
4 changes: 3 additions & 1 deletion src/ansys/mapdl/core/mapdl_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1961,7 +1961,9 @@ def _flush_stored(self):

# write to a temporary input file
def build_rand_tmp():
return os.path.join(tempfile.gettempdir(), f"tmp_{random_string()}.inp")
return tempfile.NamedTemporaryFile(
prefix="tmp_", suffix=".inp", delete=False
).name

# rare case of duplicated tmpfile (birthday problem)
tmp_filename = build_rand_tmp()
Expand Down
26 changes: 4 additions & 22 deletions src/ansys/mapdl/core/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@

from ansys.mapdl import core as pymapdl
from ansys.mapdl.core import _HAS_PYVISTA, LOG
from ansys.mapdl.core.errors import MapdlExitedError, MapdlRuntimeError
from ansys.mapdl.core.errors import MapdlExitedError

try:
import ansys.tools.report as pyansys_report
Expand Down Expand Up @@ -517,29 +517,11 @@ def last_created(filenames):

def create_temp_dir(tmpdir=None, name=None):
"""Create a new unique directory at a given temporary directory"""
if tmpdir is None:
tmpdir = tempfile.gettempdir()
path = tempfile.mkdtemp(prefix="ansys_", dir=tmpdir)

# Possible letters
letters_ = string.ascii_lowercase.replace("n", "")

def get_name():
return random_string(10, letters_)

name = name or get_name()
while os.path.exists(os.path.join(tmpdir, name)):
name = get_name()

# create dir:
path = os.path.join(tmpdir, name)

try:
if name:
path = os.path.join(path, name)
os.mkdir(path)
except: # pragma: no cover
raise MapdlRuntimeError(
"Unable to create temporary working "
f"directory {path}\nPlease specify 'run_location' argument"
)

return path

Expand Down
3 changes: 2 additions & 1 deletion tests/test_mapdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2311,9 +2311,10 @@ def test_use_vtk(mapdl):

@requires("local")
def test_remove_temp_dir_on_exit(mapdl, tmpdir):
path = os.path.join(tempfile.gettempdir(), "ansys_" + random_string())
path = tempfile.mkdtemp(prefix="ansys_")
os.makedirs(path)
filename = os.path.join(path, "file.txt")

with open(filename, "w") as f:
f.write("Hello World")
assert os.path.exists(filename)
Expand Down

0 comments on commit a7a69cb

Please sign in to comment.