python在每次“continue”之前调用一个函数

vhmi4jdf  于 2023-03-31  发布在  Python
关注(0)|答案(1)|浏览(135)

我写了许多文件,每个文件都有许多样本到数据库中。
我的代码格式如下:

files = find_my_files()

for file in files:
    try:
        check_file(file)
    except:
        logging.warning(f'{file} did not pass the check, skipping this file')
        continue
    try:
        process_file(file)
    except:
        logging.warning(f'{file} did not pass the processing, skipping this file')
        continue
    samples = get_samples(file)
        for sample in samples:
            try:
                check_sample(sample)
            except: 
                logging.warning(f'{sample} did not pass the checks, skipping this sample')
                continue
            try:
                write_to_db(sample)
            except:
                logging.warning(f'could not write{sample} to the database, skipping this sample')
                continue

我正在寻找一种方法来保存我跳过的所有样本。这可能是一个单一的样本或样本列表,如果整个文件被跳过。
我的解决方案是创建一个函数,并在continue之前每次都调用它,但我想知道是否有更好的方法?

w46czmvw

w46czmvw1#

我认为最简单的解决办法是:

try:
    completed_successfully = False
    try:
       ....
    except:
       .....

    try:
       ......
    except:
       ......
 
    try:
       write_to_db(sample):
       completed_successfully = True
    except:
       ......

finally:
    if not completed_successfully:
        .....

相关问题