image.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # greaseweazle/image/image.py
  2. #
  3. # Written & released by Keir Fraser <keir.xen@gmail.com>
  4. #
  5. # This is free and unencumbered software released into the public domain.
  6. # See the file COPYING for more details, or visit <http://unlicense.org>.
  7. import os
  8. from greaseweazle import error
  9. import greaseweazle.codec.amiga.amigados as amigados
  10. class Image:
  11. read_only = False
  12. ## Context manager for image objects created using .to_file()
  13. def __enter__(self):
  14. self.file = open(self.filename, "wb")
  15. return self
  16. def __exit__(self, type, value, tb):
  17. try:
  18. if type is None:
  19. # No error: Normal writeout.
  20. self.file.write(self.get_image())
  21. finally:
  22. # Always close the file.
  23. self.file.close()
  24. if type is not None:
  25. # An error occurred: We remove the target file.
  26. os.remove(self.filename)
  27. ## Default .to_file() constructor
  28. @classmethod
  29. def to_file(cls, name, start_cyl, nr_sides):
  30. error.check(not cls.read_only,
  31. "%s: Cannot create %s image files" % (name, cls.__name__))
  32. obj = cls(start_cyl, nr_sides)
  33. obj.filename = name
  34. return obj
  35. # Local variables:
  36. # python-indent: 4
  37. # End: