简体   繁体   中英

pause(not stop) a for loop in python

I have a for loop that read the contents from a file line by line, I need to pause the loop and if button clicked resuming the loop from where it paused. I searched the internet but I just find a stop button functionality using break for example but I don't want to break from for loop I want to pause/resuming the loop. thank you in advance for your help here my loop with stop and break, I need to add pause button functionality to it.

running[0] = True

def csv_exe():
    with open(file_path.get(), 'r') as file:
        data = csv.reader(file, delimiter=',')
        
        for line in data:
            lines= line
            if running[0]== False:
                    break
            else:
                
                    sendmMsg.set(lines)
                    print(lines)
                    time.sleep(0.5)

You can use "yield". The pseudo code would be like below.

def csv_exe():
      with open(file_path.get(), 'r') as file:
           data = csv.reader(file, delimiter=',')
           
           for line in data:
                lines= line
                if running[0]== False:
                     yield
                else:
                     sendmMsg.set(lines)
                     print(lines)
                     time.sleep(0.5)


generator=csv_exe()
while True:
  try:
     # if specific button is pressed:
         next(generator)
  except StopIteration:
     break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM