1

I have code the run..

counter =0
while 1:
    counter +=1
    print('test1')
    if counter == 12345:
        exit(1)

How can I change this code while it run so instead of exit(1) will be print('hi')

MicrosoctCprog
  • 460
  • 1
  • 3
  • 23

2 Answers2

0

I don't think this is possible to do inside a single file -- the Python interpreter appears to load the entire file in memory before running it, and reloading the current file is impossible with how Python is built.

However, you can reload a module. Knowing this, you can do something like:

# main.py
import importlib
import some_module
import time
counter = 0
while 1:
    print("Counter is", counter)
    importlib.reload(some_module)
    some_module.some_function()
    time.sleep(1)
    counter += 1
# some_module.py
def some_function():
    print("This is the original function")

Now, you can edit some_module.py, and the change will be applied to the currently running program:

...
Counter is 16
This is the original function
Counter is 17
This is the original function
Counter is 18
This is the original function
Counter is 19
This is the original function
Counter is 20
I just edited the file!
Counter is 21
I just edited the file!
Counter is 22
I just edited the file!
Counter is 23
I just edited the file!
Counter is 24
I just edited the file!
...
Danya02
  • 1,006
  • 1
  • 9
  • 24
-2

Try this code , may be help you

counter = 0
while 1:
counter += 1
print('test1')
    if counter == 12345:
       continue
print('hi')

when loop will stop it will print("hi")

Kayes Fahim
  • 672
  • 5
  • 16