简体   繁体   English

打破 python 中的 try 循环

[英]Break a try loop in python

I am trying to parse multiple sheets inside a spreadsheet from Google Sheets.我正在尝试从 Google Sheets 解析电子表格中的多个工作表。 Is running fine, except when it gets after the final sheet that cannot be found because it does not exist.运行良好,除非它到达由于不存在而无法找到的最终工作表之后。 As you can see I am doing that in a for loop with 200 iterations, but I would like to break the loop when the exception is raised.正如您所看到的,我在 200 次迭代的 for 循环中执行此操作,但是我想在引发异常时中断循环。

My code:我的代码:

def main_concat(id_file, n):
      import httplib2
      import os
      import pandas as pd
      import sys
      from apiclient import discovery

      try:

        discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                        'version=v4')
        service = discovery.build(
            'sheets',
            'v4',
            http=httplib2.Http(),
            discoveryServiceUrl=discoveryUrl,
            developerKey=key)

        spreadsheetId = id_file
        rangeName = f'Respuestas de formulario {n}!A1:L1000'
        result = service.spreadsheets().values().get(
            spreadsheetId=spreadsheetId, range=rangeName).execute()
        values = result.get('values', [])

        if not values:
            print('No data found.')
        else:
            
            df=pd.DataFrame(values)
        
        return df
      
      except SystemExit:
        print('No más hojas de formularios que extraer')
        

dfs=[]



for i in range(1,200):

  df=main_concat('1nRAte3AH0pvLMQTg-SEkiSsy4MONJnpTADOGoDLA', i)
  dfs.append(df)

Your function is returning a pandas dataframe normally.您的函数正常返回一个熊猫数据帧。 When the exception happens, the function is returning nothing ( None ) so just check the return value and if it's a None break the loop:当异常发生时,该函数不返回任何内容( None ),因此只需检查返回值,如果它是None中断循环:

for i in range(1,200):

  df=main_concat('1nRAte3AH0pvLMQTg-SEkiSsy4MONJnpTADOGoDLA', i)
  if df is None:
    break

  dfs.append(df)

Not: Please use if __name__ == "__main__" too.不是: if __name__ == "__main__"也请使用。 See: https://stackoverflow.com/a/419185/2681662参见: https : //stackoverflow.com/a/419185/2681662

Edit编辑

After your comment to João Santos I understand that you have an unknown number of files and you are trying to access 200 of them and if an exception happens it means no more files available and you want to stop the loop.在您对 João Santos 发表评论后,我了解到您的文件数量未知,您正尝试访问其中的 200 个,如果发生异常,则意味着没有更多文件可用,您想停止循环。

That's not a good way for multiple reasons.由于多种原因,这不是一个好方法。

  1. What if for some other reasons your code fails.如果由于某些其他原因您的代码失败怎么办。 Now your loop would stop.现在你的循环会停止。
  2. What if you had more then 200 files.如果你有超过 200 个文件怎么办。 Your loop would stop at 200.您的循环将在 200 处停止。

I think you need to find the file names and iterate over them.我认为您需要找到文件名并对其进行迭代。 If it is not an option, at least you can use a while loop since you are breaking it anyway.如果它不是一个选项,至少你可以使用一个while循环,因为你无论如何都会破坏它。 So if there are more then 200 files your loop would work:因此,如果有超过 200 个文件,您的循环将起作用:

i = 0
while True:
  i += 1
  df=main_concat('1nRAte3AH0pvLMQTg-SEkiSsy4MONJnpTADOGoDLA', i)
  if df is None:
    break

  dfs.append(df)

Several options, two of which I'll highlight:几个选项,我将重点介绍其中两个:

Check the return:检查退货:

for i in range(1,200):

  df=main_concat('1nRAte3AH0pvLMQTg-SEkiSsy4MONJnpTADOGoDLA', i)
  if df is None:
    break

  dfs.append(df)

Other option is to actually raise the exception.另一种选择是实际引发异常。

def main_concat(id_file, n):
      try:

        ...
        
      except SystemExit:
        print('No más hojas de formularios que extraer')
        raise
        
dfs=[]

try:
  for i in range(1,200):
    # can either catch and break, or just let it propagate.
    df=main_concat('1nRAte3AH0pvLMQTg-SEkiSsy4MONJnpTADOGoDLA', i)
    dfs.append(df)
except Exception:
  pass

Raise a general exception.提出一般例外。

try:
    #code
except Exception as e:
    print(e)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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