Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

python - How to write string to memoryview?

I want to write a bytearray type into a memoryview type. What I tried:

my_memory_view = memoryview(b'hello')
new_byte_string = bytearray(b'world')
my_memory_view = new_byte_string

but it returned:

AttributeError: can't set attribute

I know that it is possible to write into memoryview via:

my_memory_view[0] = 12  #Changes first byte

Is there a way to insert the values of the bytearray automatically into memoryview?

Edit:

I made a mistake: the error is not AttributeError the problem occurs because the type changes, but in my package I use(shared_memory) AttributeError will be shown.

question from:https://stackoverflow.com/questions/65854002/how-to-write-string-to-memoryview

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't write into your memoryview, because your memoryview is a view of a bytes object, which is immutable.

If you had a writable memoryview, such as memoryview(bytearray(b'hello')), you could do

your_memoryview[:] = whatever

to write the contents of whatever into the underlying memory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...