copying a string???

Keith Dart kdart at
Mon Aug 26 11:00:44 CEST 2002

In article <3D64ECE9.C47AB519 at>, "Joe Connellan"
<joec at> penned these words:

> The string I pass to changeString() represents an 8 bit image for
> processing. The images I am processing are very large so it is more
> efficient for my function to change the pixel values of the input image
> rather than allocating enough memory for an output image to write into.
> I need to display before and after images once the processing is done -
> at the moment my before image changes with the after.
> If I shouldn't be changing the string, do you know of a better way of
> going about it? - I do need the image data to be stored as a string -
> for PIL and PyOpenGL reasons, and I can't afford to allocate memory for
> more than one image at a time.

You might try the mmap module. This acts as both a file and a mutable
string. I have a buffer class that wraps it:

class Buffer:
	def __init__(self, size=8192):
		self.size = size
		self._fd ="/dev/zero", os.O_RDWR)
		self._buf = mmap.mmap(self._fd, size, access=mmap.ACCESS_COPY)

	def __del__(self):
	def close(self):
		self._buf = None

	def getvalue(self):
		return self._buf[:]

	def fileno(self):
		return self._fd

	# auto-delegate most attributes
	def __getattr__(self, name):
		return getattr(self._buf, name)
	def __getitem__(self, i):
		return self._buf[i]

	def __setitem__(self, i, v):
		self._buf[i] = v

	def __getslice__(self, i, j):
		return self._buf[i:j]

	def __setslice__(self, i, j, seq):
		self._buf[i:j] = seq

	def __iadd__(self, seq):
		return self

	def __len__(self):
		return self._buf.tell()

	def __str__(self):
		return self._buf[0:self._buf.tell()]

--                           ^
                           \/ \/
                           (O O)
-- --------------------oOOo~(_)~oOOo----------------------------------------
Keith Dart
<mailto:kdart at> 
Public key ID: B08B9D2C Public key: <>

More information about the Python-list mailing list