2

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.

4
  • try using break, continue or pass based on your requirements. Commented Apr 3, 2020 at 1:29
  • 4
    Reading a script and execing it is pretty crude code reuse. Why not put the logic of that script into one or more functions, and then you can import the module and run them as desired. The functions can return early if they don't have anything useful to do, or maybe raise an appropriate exception. Commented Apr 3, 2020 at 1:38
  • you really need to used exec ? Commented Apr 3, 2020 at 1:45
  • @parlad continue wouldn't work because it's not "properly" in the loop Commented Apr 3, 2020 at 1:45

2 Answers 2

1

Would it work if we just use "return"?

if transactions.shape[0] == 0:
     return
else:
     your code (happy path)
Sign up to request clarification or add additional context in comments.

3 Comments

Hi yes, I think this might work but it would imply the rest of the script is part of an else block. I wonder if there's a way to tell python to just abandon script but not program
Hey, you're right, this wouldn't be ideal even if it works. Following for other solutions..
You could remove the else statement and just do the rest of the code at the same indentation level of the if statement. That else is just useless.
0

Just add a try...except to your exec() instruction:

## Your code
## ...
for d in daterange:
    start_date = d.strftime("%Y-%m-%d")
    try:
        exec(open("run_transactions.py").read())
    except SystemExit:
        pass

And in your transaction.py you can just keep using sys.exit(0).

From the docs

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

So basically you intercept that execption and just ignore it and keep running your loop.

EDIT:

Example of use:

for i in range(0, 5):
    try:
        exec(open("file.py").read())
    except SystemExit:
        print(f"System Exit on i = {i}")
    else:
        print(f"Normal {i}")

file.py:

import random
import sys

x = random.randint(0, 5)
if x >= 3:
    print("sys.exit(0)")
    sys.exit(0)
else:
    print(f"{x} is smaller than 3. No sys.exit(0)")

An example (due to the random behavior) output:

1 is smaller than 3. No sys.exit(0)
Normal 0
sys.exit(0)
System Exit on i = 1
sys.exit(0)
System Exit on i = 2
2 is smaller than 3. No sys.exit(0)
Normal 3
sys.exit(0)
System Exit on i = 4

3 Comments

Hi, I gave this a try but it did still sys exit when instead I hoped that it would pass and move to the next iteration of the loop. Any ideas?
I tried to print the exception to see if I had used the wrong one ` try: exec(open("run_transactions.py").read()) except Exception as e: print(e)` but this still didn't catch, I just got 'Process finished with exit code 0'
@DougFir, edited answer with an example of use. It works fine. Maybe there is something on your code that you are not telling us.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.