From 41563507081637d4088d69e18a220394dadba9ea Mon Sep 17 00:00:00 2001 From: Alessio Quaglino Date: Mon, 10 Feb 2025 04:32:32 -0800 Subject: [PATCH] Add to_file function to save the Spec to a file. Fixes #2415. PiperOrigin-RevId: 725161617 Change-Id: I6c374cc7f7cb3f1da1cc0da531dd7e5be5d62b6a --- python/mujoco/specs.cc | 6 ++++++ python/mujoco/specs_test.py | 8 +++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/python/mujoco/specs.cc b/python/mujoco/specs.cc index 5031f05c..98faf44f 100644 --- a/python/mujoco/specs.cc +++ b/python/mujoco/specs.cc @@ -518,6 +518,12 @@ PYBIND11_MODULE(_specs, m) { } return std::string(buf.get()); }); + mjSpec.def("to_file", [](MjSpec& self, std::string& file) { + std::array err; + if (mj_saveXML(self.ptr, file.c_str(), err.data(), err.size()) < 0) { + throw FatalError(std::string(err.data())); + } + }); mjSpec.def( "add_default", [](MjSpec* spec, std::string& classname, diff --git a/python/mujoco/specs_test.py b/python/mujoco/specs_test.py index 2806d01a..d7eb9b0c 100644 --- a/python/mujoco/specs_test.py +++ b/python/mujoco/specs_test.py @@ -113,9 +113,7 @@ class SpecsTest(absltest.TestCase): self.assertEqual(model.nuser_site, 6) np.testing.assert_array_equal(model.site_user[0], [1, 2, 3, 4, 5, 6]) - self.assertEqual( - spec.to_xml(), - textwrap.dedent("""\ + xml = textwrap.dedent("""\ @@ -127,8 +125,8 @@ class SpecsTest(absltest.TestCase): - """), - ) + """) + self.assertEqual(spec.to_xml(), xml) def test_kwarg(self): # Create a spec.