I have a loop of the form:
import pandas as pd
import os
import sys
range_start_date = '2020-01-01'
range_end_date = '2020-01-10'
daterange = pd.date_range(range_start_date, range_end_date) # creates a range of dates list
for d in daterange:
start_date = d.strftime("%Y-%m-%d")
exec(open("run_transactions.py").read())
Within run_transactions.py I have a particular line of code like this:
import sys
if transactions.shape[0] == 0:
sys.exit(0)
I do this because further down in the script I apply some data wrangling to data frame called transactions. But, sometimes transactions has no data, in which case I exit.
However, since I am calling the script as part of a loop, with a new date d on each loop iteration, I don't want to exit the program entirely, instead I want to skip the rest of the script only, then continue the loop.
Is there a way for me to tell python that if if transactions.shape[0] == 0 then to stop running this iteration of run_transactions.py and to proceed to the next part of the loop? Using sys.exit(0) exists the program entirely and breaks the loop which is not what I want.
execing it is pretty crude code reuse. Why not put the logic of that script into one or more functions, and then you canimportthe module and run them as desired. The functions canreturnearly if they don't have anything useful to do, or maybe raise an appropriate exception.