运行 Python 脚本 X Number 如果出错

Run Python Script X Number Times if Error

我正在尝试 运行 下面的脚本,其中四个块引用了其他四个脚本; LIBERTY、TRA、GTS 和 SOPI。我遇到的问题是单个脚本可能 运行 出错,但会再次 运行 清除一次。

有没有办法让每个块循环到 运行 最多 3 次?对于每个块而不是整体。如果收到错误 3 次,对于那个 chunk/outside 脚本,它将提供一个错误。

代码,

import os

# Call on each scraper script to run

# LIBERTY
os.chdir("S:\Supply\Risk Management\Daily auto downloads\Storage\LIBERTY")
exec(open('LIBERTYScraper.py').read())

# TRA
os.chdir("S:\Supply\Risk Management\Daily auto downloads\Storage\TRA")
exec(open('TRAScraper.py').read())

# GTS
os.chdir("S:\Supply\Risk Management\Daily auto downloads\Storage\GTS")
exec(open('GSIScraper.py').read())

# SOPI 
os.chdir("S:\Supply\Risk Management\Daily auto downloads\Storage\SOPI")
exec(open('SOPIScraper.py').read())

# Finish statement
print("Scraper data pulls have been completed.")

像这样的东西应该可以工作:

import os

# Call on each scraper script to run

# LIBERTY
os.chdir("S:\Supply\Risk Management\Daily auto downloads\Storage\LIBERTY")
with open('LIBERTYScraper.py') as f:
    for _ in range(3):
        try:
            exec(f.read())
            break;
         except Exception: # generaly not a great idea, put a more refined exception
             continue;

# Finish statement
print("Scraper data pulls have been completed.")

像这样:

for i in range(3):
  try:
    os.chdir("S:\Supply\Risk Management\Daily auto downloads\Storage\LIBERTY")
    exec(open('LIBERTYScraper.py').read())
    break
  except:
    print("Error opening file")