Search code examples
pythonnameerror

Python NameError 'xxx' not defined when executing a .py script from another .py script


I have a script named schedule.py:

# Script to schedule and trigger batch run every day of month at 6.30p.m.

from datetime import date
import time
import schedule

def job():
    exec(open("main.py").read())
    print('Batch run completed')
        
schedule.every().day.at("18:30").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

This schedule.py will execute the other Python script, main.py.

main.py is used to process the data, so it involves pandas, numpy. When I run main.py directly, there was no error at all. But when I try to run main.py through schedule.py, it returns error:

NameError: ("name 'np' is not defined", 'occurred at index 0')

After that, I added

import numpy as py

into schedule.py to solve the error above.

But after solving the np not defined error, another error occurs when executing main.py through schedule.py:

NameError: name 'avg_util_l3m' is not defined

This variable avg_util_l3m is a variable used in main.py. The part of main.py which uses the variable as below:

# lots of code...

avg_util_l3m = joined_df['AverageUtilizationL3M']
avg_util_l3m = joined_df['ProdType'].apply(lambda x: avg_util_l3m if x != 'Non-Revolving' else -9999)

# lots of code...

Does anyone know why will this error happen and how do I solve it?

Note:

  1. There are no errors at all while running main.py directly in cmd. So I think that np and avg_util_l3m are defined correctly in main.py.

  2. The full code of schedule.py is as above. It does not contain variables like np or avg_util_l3m. Only main.py uses the variables.


Solution

  • I had a similar issue in the past and all I can tell you is that exec() is slow and unpredictable, use anything else and I doubt you will have that same error. If your code is too long to simply import, try and use an alternative like runpy.