【问题标题】:while loop with try/exception stay in loop until read all rows of df / ignore exception带有try/exception的while循环保持循环,直到读取df的所有行/忽略异常
【发布时间】:2021-06-20 09:31:57
【问题描述】:

这是一段卡在异常循环中的 Python。我阅读了thisthis 以及更多内容,但不幸的是找不到我正在寻找的答案。它工作正常,直到它陷入 i=8 的异常(即 git_url 由所有者存档)。我该如何解决?我不希望它在 i=8 时中断/get_stuck,因为它仍然需要读取其余部分。

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  

【问题讨论】:

    标签: python while-loop git-clone try-except


    【解决方案1】:

    一旦continue被调用,它会在i += 1被调用之前跳回顶部。尝试将该语句向上移动,例如:

    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  
    

    这样它就不会卡在有问题的迭代中,让我知道这是怎么回事:)

    【讨论】:

    • 谢谢,它有效。我应该早点问的。
    • 兔子洞调试代码很容易迷路:P
    猜你喜欢
    • 1970-01-01
    • 2016-09-08
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    相关资源
    最近更新 更多