I want to change variables inside the code by accessing them from the outside while executing Python code.
I want to access and change the variable a from the outside while executing Python code. Consider the code (test1.py) that always stores the contents of the text file "TEST.txt" in the variable a as shown below. Even if the contents of TEST.txt are changed while test1.py is being executed, the value of the variable a in test1.py is not updated. (The value of TEST.txt before the change remains)
Read the contents of TEST.txt into memory. test1.py and test2.py share memory. test1.py is reading the memory value into variable a. test2.py changes the value of memory. Whenever test1.py is executed, the value is read from memory and stored in the variable a. When test2.py is executed, the memory value is changed, and test1.py reads the updated value in test2.py.
Below is the code that implements the above behavior. Use mmap.mmap-> You can store the contents of the read file in memory.
Please drive test2.py after running test1.py first.
/test1.py
import mmap
with open("example.txt", "r+b") as f:
#mmap.mmap(fileno, length[, tagname[, access[, offset]]])Map length bytes from the specified file.
#If length is 0, the maximum length of the map is the current file size.
mm = mmap.mmap(f.fileno(), 0) #Read the contents of the file and write to mm. mm is the sequence of bits"01010101..." //mmap.mmap(fileno, length[, tagname[, access[, offset]]])
while True:
mm.seek(0) #Read memory mm from the head(seek(0)), Store the read value in mm.
mode=mm.readline() #Write the contents of memory mm to the variable mode.
print(mode)
/test2.py
import mmap
with open("example.txt", "r+b") as f:
#Read the contents of the file and write to mm. mm is the sequence of bits"01010101..."
mm = mmap.mmap(f.fileno(), 0)
#Memory mm b"01"Rewrite to. example example.Since the length of the txt data is 2, specify the length of the data to be written as 2. example example.Data with a length different from the txt data cannot be written.
mm[:] = b"01"
/example.txt
#Please write the data in binary. To write to memory
00
Recommended Posts