python 、mmap 實現內存數據共享
阿新 • • 發佈:2017-05-04
python access import 字符串 二進制
import mmap mmap_file = None##從內存中讀取信息,def read_mmap_info(): global mmap_file mmap_file.seek(0) ##把二進制轉換為字符串 info_str=mmap_file.read().translate(None, b‘\x00‘).decode() print(info_str)##如果內存中沒有對應信息,則向內存中寫信息以供下次調用使用def get_mmap_info(): global mmap_file ##第二個參數1024是設定的內存大小,單位:字節。如果內容較多,可以調大一點 mmap_file = mmap.mmap(-1, 1024, access = mmap.ACCESS_WRITE, tagname = ‘share_mmap‘) ##讀取有效比特數,不包括空比特 cnt=mmap_file.read_byte() if cnt==0: print("Load data to memory") mmap_file = mmap.mmap(0, 1024, access = mmap.ACCESS_WRITE, tagname = ‘share_mmap‘) mmap_file.write(b"This is the test data") else : print("The data is in memory") read_mmap_info()##修改內存塊中的數據def reset_mmp_info: global mmap_file mmap_file.seek(0) mmap_file.write(b‘\x00‘) mmap_file.write(b"Load data to memory agine")if __name__=="__main__": get_mmap_info() 說明:如果是使用python自帶的IDE,請重新打開一次此文件運行測試數據裝載到內存後的結果
python 、mmap 實現內存數據共享