Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 28 additions & 16 deletions python/mujoco/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,20 @@ def to_zip(spec: _specs.MjSpec, file: Union[str, IO[bytes]]) -> None:
"""
files_to_zip = spec.assets
files_to_zip[spec.modelname + '.xml'] = spec.to_xml()
opened = False
if isinstance(file, str):
directory = os.path.dirname(file)
os.makedirs(directory, exist_ok=True)
file = open(file, 'wb')
with zipfile.ZipFile(file, 'w') as zip_file:
for filename, contents in files_to_zip.items():
zip_info = zipfile.ZipInfo(filename)
zip_file.writestr(zip_info, contents)
opened = True
try:
with zipfile.ZipFile(file, 'w') as zip_file:
for filename, contents in files_to_zip.items():
zip_info = zipfile.ZipInfo(filename)
zip_file.writestr(zip_info, contents)
finally:
if opened:
file.close()


def from_zip(file: Union[str, IO[bytes]]) -> _specs.MjSpec:
Expand All @@ -127,20 +133,26 @@ def from_zip(file: Union[str, IO[bytes]]) -> _specs.MjSpec:
"""
assets = {}
xml_string = None
opened = False
if isinstance(file, str):
file = open(file, 'rb')
if not zipfile.is_zipfile(file):
raise ValueError(f'File {file} is not a zip file.')
with zipfile.ZipFile(file, 'r') as zip_file:
xml_dir = None
for zip_info in zip_file.infolist():
if not zip_info.filename.endswith(os.path.sep):
with zip_file.open(zip_info.filename) as f:
if zip_info.filename.endswith('.xml'):
xml_string = f.read()
xml_dir = os.path.dirname(zip_info.filename)
else:
assets[zip_info.filename] = f.read()
opened = True
try:
if not zipfile.is_zipfile(file):
raise ValueError(f'File {file} is not a zip file.')
with zipfile.ZipFile(file, 'r') as zip_file:
xml_dir = None
for zip_info in zip_file.infolist():
if not zip_info.filename.endswith(os.path.sep):
with zip_file.open(zip_info.filename) as f:
if zip_info.filename.endswith('.xml'):
xml_string = f.read()
xml_dir = os.path.dirname(zip_info.filename)
else:
assets[zip_info.filename] = f.read()
finally:
if opened:
file.close()

if not xml_string:
raise ValueError('No XML file found in zip file.')
Expand Down
2 changes: 1 addition & 1 deletion python/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@

def get_long_description():
"""Creates a long description for the package from bundled markdown files."""
current_dir = os.path.dirname('__file__')
current_dir = os.path.dirname(__file__)
with open(os.path.join(current_dir, 'README.md')) as f:
description = f.read()
try:
Expand Down