Cordell Jones
Cordell Jones

Reputation: 93

Run Python Script X Number Times if Error

I am trying to run the below script with the four chunks referencing four other scripts; LIBERTY, TRA, GTS, and SOPI. The issue I have is a single script might run into an error but will clear once run again.

Is there a way to make a loop to run a max of 3 times for each chunk? For each chunk and not as a whole. If an error is received three times, for that chunk/outside script, it will provide an error.

The code,

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.")

Upvotes: 0

Views: 270

Answers (2)

Devang Sanghani
Devang Sanghani

Reputation: 780

Something like this :

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")

Upvotes: 1

Robin Dillen
Robin Dillen

Reputation: 712

Something like this should work:

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.")

Upvotes: 2

Related Questions