From 9d741a76924cf27827a4f26d23e0fc243eafbaca Mon Sep 17 00:00:00 2001 From: Mirko Bunse Date: Wed, 14 Aug 2024 08:59:20 +0200 Subject: [PATCH] to_file exports to existing and non-existing directories (#10) --- critdd/tests/readme.py | 2 +- critdd/tests/two_d.py | 2 +- critdd/tikz.py | 12 +++++++++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/critdd/tests/readme.py b/critdd/tests/readme.py index 0029d8e..ea93523 100644 --- a/critdd/tests/readme.py +++ b/critdd/tests/readme.py @@ -27,7 +27,7 @@ def test_readme(self): self.assertTrue(["clf3", "clf5"] in groups) # check the tikz export - output_path = "__example__.pdf" + output_path = "__unittest__/readme.pdf" if os.path.exists(output_path): os.remove(output_path) # make sure the file does not exist already diagram.to_file( diff --git a/critdd/tests/two_d.py b/critdd/tests/two_d.py index c5e81c9..d534dea 100644 --- a/critdd/tests/two_d.py +++ b/critdd/tests/two_d.py @@ -28,7 +28,7 @@ def test_2d(self): self.assertTrue(["clf3", "clf5"] in groups) # check the tikz export - output_path = "__2d_example__.pdf" + output_path = "__unittest__/two_d.pdf" if os.path.exists(output_path): os.remove(output_path) # make sure the file does not exist already diagrams.to_file( diff --git a/critdd/tikz.py b/critdd/tikz.py index ea20325..2aac305 100644 --- a/critdd/tikz.py +++ b/critdd/tikz.py @@ -39,16 +39,26 @@ def _merge_dicts(a, b): def to_file(path, tikz_code): """Export the tikz_code to a file.""" root, ext = os.path.splitext(path) + root_dir = os.path.dirname(root) if ext not in [ ".tex", ".tikz", ".pdf", ".svg", ".png" ]: raise ValueError("Unknown file path extension") if ext in [ ".pdf", ".svg", ".png" ]: path = root + ".tex" + if root_dir != "": # ensure that the root directory exists + if not os.path.isdir(root_dir): + os.makedirs(root_dir) with open(path, "w") as f: # store the Tikz code in a .tex or .tikz file f.write(tikz_code) if ext in [ ".tex", ".tikz" ]: return None # we are done here pdflatex = subprocess.Popen( - ["pdflatex", "-interaction=nonstopmode", "-halt-on-error", path], + [ + "pdflatex", + "-interaction=nonstopmode", + "-halt-on-error", + f"-output-directory={root_dir}", + path + ], stdout = subprocess.PIPE ) (out, err) = pdflatex.communicate() # convert to PDF