0

I have a file that looks like this called myLoop.py

for i in range(100):
     print(i)

I run the file like so: python3 myLoop.py

I want to stop the code after reaching i = 10

Then, I want to manually start the code again by typing python3 myLoop.py or whatever necessary into the terminal, to have the code pick up after i = 10.

Then, I want the code to then stop at i = 30, then continue via a manual command again until the code completes at i = 99.

To be clear, I want to manually send a statement to the terminal in order to have the code pick up where it left off.

I want to use the pickle module to accomplish this, here are some links I've looked through related to it:

https://docs.python.org/3/library/pickle.html

https://www.geeksforgeeks.org/understanding-python-pickling-example/

https://realpython.com/python-pickle-module/

How to stop a for loop while in execution

This post is said to be a duplicate of the following posts, but neither provide any examples of the use of the pickle module for this purpose. The first post simply has an embedded link of the first URL I've read, and the other provides an example of JSON's use case. This post is not a duplicate of either.

Saving the state of a program to allow it to be resumed

Best method of saving data

1 Answers1

0

Maybe this can help you

start = 0
try:
    with open("state.txt", "rt") as fp:
        state = fp.read()

    if int(state) > 0:
        start = int(state) + 1
except:
    pass
for i in range(start, 100):

    print(i)
    if i == 10 or i == 30:
        with open("state.txt", "wt") as fp:
            fp.write(f"{i}")
            break