0

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?

1
  • 1
    No. That's a horrible, horrible practice called "self-modifying code". Some early languages allowed that (COBOL, for instance), but it was soon realized that it caused code to be unmaintainable. Commented Aug 14, 2023 at 1:14

1 Answer 1

0

Your code is writing the file every 2 seconds, however what it is writing is not changing. The in-memory python process reads a = 0 once (or a = 1 if it has run already), computes str(a+1), and writes that. The next loop, a+1 has not changed, so it writes the same value.

The simple "fix" here is to add the line a = a + 1 in the body of the while loop, if that's what you want.

If your goal is for the python program reloading itself based on its current value on the disk, look at How do I save and restore multiple variables in python? for an example.

A more robust approach than modifying the source code would be to store the value you're interested in (a here) on disk, separate from the source code. Look at the pickle module for a good example of how to serialize python data to disk, or use a simple plaintext format like json (or just a file containing a number, if that's all you want).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.