Standard_Intelligence_Dev / code_df_custom.py
MaksG's picture
Update code_df_custom.py
3c6168b verified
raw
history blame
1.03 kB
import pandas as pd
import traceback
def run_code(file, code):
scope = {'pd': pd}
if file:
print('file ok')
df = pd.read_excel(file)
scope['df'] = df
try:
# Attempt to execute the user's code
exec(code, scope, scope)
except Exception as e:
# Catch any exceptions that occur and print the error message
error_msg = traceback.format_exc()
print(f"Error executing user code: {error_msg}")
scope['new_df'] = df # Use the original df if error occurs
return scope['new_df'], error_msg # Return the error message along with the df
print(scope.keys())
if 'new_df' not in scope:
print("new_df not defined")
scope['new_df'] = df.copy()
new_df = scope['new_df']
return new_df, None # Return None as the error message when execution is successful
else:
print("No file provided")
return pd.DataFrame(), "No file provided"