Search code examples
pythonwhile-loopgit-clonetry-except

while loop with try/exception stay in loop until read all rows of df / ignore exception


Here is a piece of Python that got stuck on the exception loop. I read this and this and many more and unfortunately could not find the answer I am looking for. It works fine until it gets stuck in exception for i=8 (i.e. the git_url is archived by owner). How can I solve it? I don't want it to break/get_stuck when i=8 because it still needs to read the rest.

i=7
while i<10:
  try:
    Repo.clone_from(df.git_url[i],repo_dir) #clone repositores for each url
  except:
    print("error")
    continue
  else:
      for f in glob.iglob("repo_dir/**/*.rb"):
        txt = open(f, "r") 
        # let's say txt is a code file that I want to extract data from 
        for line in txt:
            print(line)  
  shutil.rmtree(repo_dir)
  os.makedirs(repo_dir)
  i+=1  

Solution

  • Once continue is called, it will skip back to the top before i += 1 is called. Try moving that statement higher up, something like:

    i=7
    while i<10:
      try:
        Repo.clone_from(df.git_url[i],repo_dir) #clone repositores for each url
      except:
        print("error")
        i += 1
        continue
      else:
          for f in glob.iglob("repo_dir/**/*.rb"):
            txt = open(f, "r") 
            # let's say txt is a code file that I want to extract data from 
            for line in txt:
                print(line)  
      shutil.rmtree(repo_dir)
      os.makedirs(repo_dir)
      i += 1  
    

    That way it won't get stuck on the problematic iteration, let me know how this goes :)