Skip to content

Commit

Permalink
to_file exports to existing and non-existing directories (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
mirkobunse authored Aug 14, 2024
1 parent edbddae commit 9d741a7
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
2 changes: 1 addition & 1 deletion critdd/tests/readme.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion critdd/tests/two_d.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
12 changes: 11 additions & 1 deletion critdd/tikz.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 9d741a7

Please sign in to comment.