This is just a simplified example, I know this isn't the best way to do it, but I'm trying it for something else. Is it possible to replace a line of a Python script using its own code, while having the code stay running?
I have this code:
import re
a = 0
f = open("main.py","r")
lines = f.read()
lines = re.sub(r"a = .+\n",r"a = " + str(a+1) + "\n",lines,count=1)
f.close()
f = open("main.py","w")
f.writelines(lines)
f.close()
Each time this is run, a is added to by 1. However, when I try to loop it:
import re
import time
a = 0
while True:
f = open("main.py","r")
lines = f.read()
lines = re.sub(r"a = .+\n",r"a = " + str(a+1) + "\n",lines,count=1)
f.close()
f = open("main.py","w")
f.writelines(lines)
f.close()
time.sleep(2)
It should add 1 to a every 2 seconds, but it only changes it once the code is finished (or when I end the code, since the while loop is infinite). Is there some way to continue changing the code without having to end the code?