Imagine a python script that will take a long time to run, what will happen if I modify it while it's running? Will the result be different?
-
19The program is loaded into your main memory. If you change the source file, nothing happens. Imagine the CPU would read instructions from the hard drive... – Felix Kling Mar 14 '11 at 09:50
-
23@Felix: That's called "Execute-in-Place" (XIP). – Ignacio Vazquez-Abrams Mar 14 '11 at 09:52
-
3You may dynamically reload the code of modules, see http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module – Iliyan Bobev Oct 09 '12 at 18:45
-
7Note that Windows batch files *do* execute in place, so this isn't a hypothetical question, there are languages out there that behave this way. – yoyo Aug 08 '18 at 21:03
-
1Is it still the case if I have multiple .py files with source code, and the program calls these different files / classes during runtime? still the original version is used? what if my program does not fit totally in the RAM? – Gemini Jul 31 '19 at 18:51
-
@Gemini Lack of RAM is solved by the OS, not by python; it's performed by swapping sections of memory in RAM onto your hard drive until they're accessed again. However, if that happens, you're in deep trouble, since things start becoming really slow really fast. See [thrashing](https://en.wikipedia.org/wiki/Thrashing_(computer_science)#:~:text=Thrashing%20is%20a%20state%20in,%2C%20and%20'swapping'%20more.&text=The%20CPU%20is%20busy%20in,page%20refers%20to%20another%20page.). – Nearoo Nov 24 '21 at 10:59
-
As @yoyo stated, windows batch files do execute in place. Modifying a batch file wile it is running causes all sorts of errors. Even if you are just adding comments. This is a very valid question. – JG1212 Sep 26 '22 at 12:18
9 Answers
Nothing, because Python precompiles your script into a PYC file and launches that.
However, if some kind of exception occurs, you may get a slightly misleading explanation, because line X may have different code than before you started the script.
-
16
-
73But what if you re-launch while running, when the new pyc files overwrite the old, will that cause problems in the program that was already running or not? – hiddensunset4 May 03 '12 at 01:31
-
34Nothing happens. I also checked it in a small test. What happens: the pyc is only the compilate. And this compilate gets loaded into the RAM and then executed. So it's always possible to change the program, recompile and run another instance e.g. in a different console. – Chris Nov 07 '14 at 12:28
-
12@Chris I started an instance of my python script in one console. While that was running, I changed two lines of code and started another instance in a separate console. After awhile, I got an error returned from the first console about the two lines of code that I changed after starting it! pls help – double_j Jan 26 '15 at 19:44
-
2@double_j: As to my knowledge this can not be due to the changes in the meantime. Maybe you had an mistake in the first place or you access / modify the same resources with both scripts and that leads to problems. – Chris May 25 '15 at 12:39
-
23@Chris I think I know what happens here. If you modify a script and save while it's running, and the previous version errors, in the traceback readout, it opens the current version of the file and makes the traceback look different than when you started. I have seen this myself on several occasions. – double_j Jun 09 '16 at 17:41
-
I executed, edited, saved and I got an error on a call to multiprocessing.Pool due a different amount of values expected. So maybe when dealing with multiple threads there is a risk of messing things? – fuyas Aug 17 '17 at 10:59
-
1I have also observed a similar thing as mentioned by @fuyas. In my case also, it happened on a call to multiprocessing.Pool – Sidak May 06 '18 at 15:42
-
@fuyas: `multiprocessing` starts a new process, so perhaps something got reimported. – user1071847 Sep 27 '18 at 14:10
-
1Pardon me if I am wrong. I was studying about swap space and memory management. So if the memory gets too full and some other process is currently running then the OS may decide to remove(not swap) some pages of our program from memory thinking 'it is already stored in disk so no need to store it in swap space'. In such a case, when our program is scheduled to run, OS would retrieve the now edited file. Wouldn't this cause an error while running the scipt? – Black Jack 21 Feb 26 '19 at 17:45
-
Since you mention PYC, that makes me wonder, is this implementation-dependent? – wjandrea Apr 03 '19 at 17:29
-
@Lixas I'm aware that PYC files are for CPython. I'm asking if some implementations don't precompile, or if they don't have the problem of printing the wrong line. – wjandrea Apr 04 '19 at 13:13
-
1this might not be true, I noticed my script hangs when I modify my script, and runs to completion when I don't modify it! – cryanbhu Nov 06 '20 at 09:10
-
A more interesting question would be: Can I modify the behavior of a Python program **after** it is launched? – Yan King Yin Aug 30 '21 at 09:44
-
1@YanKingYin A module is only executed once, and the result of the execution are the module objects in memory, _python_ objects, unrelated to py or pyc code. Check my answer below. – Nearoo Nov 24 '21 at 10:41
-
I actually had another use-case, where I edit my code and run it again, while the previous version is still running. I have only understood that this was a different use-case after reading your answer. Maybe I'll ask a different question on my use-case, but a more in-depth answer here is good anyway. – anatolyg Nov 24 '21 at 11:33
-
From experience, modifying source while running and then hitting an exception can result in a explanation that is a lot more than slightly misleading. – cowlinator May 24 '22 at 21:17
When you run a python program and the interpreter is started up, the first thing that happens is the following:
- the module
sys
andbuiltins
is initialized - the
__main__
module is initialized, which is the file you gave as an argument to the interpreter; this causes your code to execute
When a module is initialized, it's code is run, defining classes, variables, and functions in the process. The first step of your module (i.e. main file) will probably be to import other modules, which will again be initialized in just the same way; their resulting namespaces are then made available for your module to use. The result of an importing process is in part a module (python-) object in memory. This object does have fields that point to the .py and .pyc content, but these are not evaluated anymore: module objects are cached and their source never run twice. Hence, modifying the module afterwards on disk has no effect on the execution. It can have an effect when the source is read for introspective purposes, such as when exceptions are thrown, or via the module inspect.
This is why the check if __name__ == "__main__"
is necessary when adding code that is not intended to run when the module is imported. Running the file as main is equivalent to that file being imported, with the exception of __name__
having a different value.
Sources:
- What happens when a module is imported: The import system
- What happens when the interpreter starts: Top Level Components
- What's the
__main__
module:__main__
- Top-level code environment

- 4,454
- 3
- 28
- 39
This is a fun question. The answer is that "it depends".
Consider the following code:
"Example script showing bad things you can do with python."
import os
print('this is a good script')
with open(__file__, 'w') as fdesc:
fdesc.write('print("this is a bad script")')
import bad
Try saving the above as "/tmp/bad.py" then do "cd /tmp" and finally "python3 bad.py" and see what happens.
On my ubuntu 20 system I see the output:
this is a good script
this is a bad script
So again, the answer to your question is "it depends". If you don't do anything funky then the script is in memory and you are fine. But python is a pretty dynamic language so there are a variety of ways to modify your "script" and have it affect the output.
If you aren't trying to do anything funky, then probably one of the things to watch out for are imports inside functions.
Below is another example which illustrates the idea (save as "/tmp/modify.py" and do "cd /tmp" and then "python3 modify.py" to run). The fiddle
function defined below simulates you modifying the script while it is running (if desired, you could remove the fiddle function, put in a time.sleep(300)
at the second to last line, and modify the file yourself).
The point is that since the show
function is doing an import inside the function instead of at the top of the module, the import won't happen until the function is called. If you have modified the script before you call show
, then your modified version of the script will be used.
If you are seeing surprising or unexpected behavior from modifying a running script, I would suggest looking for import statements inside functions. There are sometimes good reasons to do that sort of thing so you will see it in people's code as well as some libraries from time to time.
Below is the demonstration of how an import inside a function can cause strange effects. You can try this as is vs commenting out the call to the fiddle
function to see the effect of modifying a script while it is running.
"Example showing import in a function"
import time
def yell(msg):
"Yell a msg"
return f'#{msg}#'
def show(msg):
"Print a message nicely"
import modify
print(modify.yell(msg))
def fiddle():
orig = open(__file__).read()
with open(__file__, 'w') as fdesc:
modified = orig.replace('{' + 'msg' + '}', '{msg.upper()}')
fdesc.write(modified)
fiddle()
show('What do you think?')

- 975
- 1
- 10
- 16
-
All the other answers seem to assume (without making this explicit) that everything that runs is imported before the modification happens. While this is true in many (most?) cases, it is not always the case, and in any case should be stated as an explicit assumption. – Gerhard Apr 19 '23 at 15:10
No, the result will not reflect the changes once saved. The result will not change when running regular python files. You will have to save your changes and re-run your program.

- 609
- 8
- 11
If you run the following script:
from time import sleep
print("Printing hello world in: ")
for i in range(10, 0, -1):
print(f"{i}...")
sleep(1)
print("Hello World!")
Then change "Hello World!" to "Hello StackOverflow!" while it's counting down, it will still output "Hello World".

- 91
- 3
-
1As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 25 '21 at 10:42
-
1Excuse me? How is this unclear or worthy of a downvote in the slightest? It provides an example of "a python script that will take a long time to run", and explains what will happen. – ITR Dec 13 '21 at 11:03
Nothing, as this answer. Besides, I did experiment when multiprocessing
is involved. Save the script below as x.py
:
import multiprocessing
import time
def f(x):
print(x)
time.sleep(10)
if __name__ == '__main__':
with multiprocessing.Pool(2) as pool:
for _ in pool.imap(f, ['hello'] * 5):
pass
After python3 x.py
and after the first two 'hello' being printed out, I modified ['hello']
to ['world']
and observed what happend. Nothing interesting happened. The result was still:
hello
hello
hello
hello
hello

- 143
- 1
- 7
It happens nothing. Once the script is loaded in memory and running it will keep like this.
An "auto-reloading" feature can be implemented anyway in your code, like Flask and other frameworks does.

- 1,094
- 6
- 12
This is slightly different from what you describe in your question, but it works:
my_string = "Hello World!"
line = input(">>> ")
exec(line)
print(my_string)
Test run:
>>> print("Hey")
Hey
Hello World!
>>> my_string = "Goodbye, World"
Goodbye, World
See, you can change the behavior of your "loaded" code dynamically.

- 1,189
- 1
- 10
- 25
depending. if a python script links to other modified file, then will load newer version ofcourse. but if source doesnt point to any other file it'll just run all script from cache as long as its run. changes will be visible next time...
and if about auto-applying changes when they're made - yes, @pcbacterio was correct. its possible to do thar but script which does it just remembers last action/thing what was doing and checks when the file is modified to rerun it (so its almost invisible)
=]

- 39
- 6