Coverage for trimesh/path/exchange/export.py: 96%
28 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-06-24 04:40 +0000
« prev ^ index » next coverage.py v7.14.1, created at 2026-06-24 04:40 +0000
1import os
3from ... import util
4from ...exchange import ply
5from . import dxf, svg_io
8def export_path(path, file_type=None, file_obj=None, **kwargs):
9 """
10 Export a Path object to a file- like object, or to a filename
12 Parameters
13 ---------
14 file_obj: None, str, or file object
15 A filename string or a file-like object
16 file_type: None or str
17 File type, e.g.: 'svg', 'dxf'
18 kwargs : passed to loader
20 Returns
21 ---------
22 exported : str or bytes
23 Data exported
24 """
25 # if file object is a string it is probably a file path
26 # so we can split the extension to set the file type
27 if isinstance(file_obj, str):
28 file_type = util.split_extension(file_obj)
30 # run the export
31 export = _path_exporters[file_type](path, **kwargs)
32 # if we've been passed files write the data
33 _write_export(export=export, file_obj=file_obj)
35 return export
38def export_dict(path):
39 """
40 Export a path as a dict of kwargs for the Path constructor.
41 """
42 export_entities = [e.to_dict() for e in path.entities]
43 export_object = {"entities": export_entities, "vertices": path.vertices.tolist()}
44 return export_object
47def _write_export(export, file_obj=None):
48 """
49 Write a string to a file.
50 If file_obj isn't specified, return the string
52 Parameters
53 ---------
54 export: a string of the export data
55 file_obj: a file-like object or a filename
56 """
58 if file_obj is None:
59 return export
61 if hasattr(file_obj, "write"):
62 out_file = file_obj
63 else:
64 # expand user and relative paths
65 file_path = os.path.abspath(os.path.expanduser(file_obj))
66 out_file = open(file_path, "wb")
67 try:
68 out_file.write(export)
69 except TypeError:
70 out_file.write(export.encode("utf-8"))
72 out_file.close()
74 return export
77_path_exporters = {
78 "dxf": dxf.export_dxf,
79 "svg": svg_io.export_svg,
80 "ply": ply.export_ply,
81 "dict": export_dict,
82}