MaksG commited on
Commit
3c6168b
1 Parent(s): b901c76

Update code_df_custom.py

Browse files
Files changed (1) hide show
  1. code_df_custom.py +23 -25
code_df_custom.py CHANGED
@@ -1,32 +1,30 @@
1
  import pandas as pd
2
-
3
- def load_excel(file):
4
- df = pd.read_excel(file)
5
- return file, df
6
 
7
  def run_code(file, code):
8
  scope = {'pd': pd}
9
  if file:
10
- print('file ok')
11
- df = pd.read_excel(file)
12
-
13
- scope['df'] = df
14
- exec(code, scope, scope)
15
- print(scope.keys())
16
- if not 'new_df' in scope:
17
- print("new_df not defined")
18
- scope['new_df'] = df.copy()
19
- new_df = scope['new_df']
20
-
21
- return new_df
22
- else:
23
- print(f"No file provided")
24
- df = pd.DataFrame()
25
- return df
26
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- def export_df(df, filename):
29
- filename = filename.replace('.xlsx', '_coded.xlsx')
30
- df.to_excel(filename, index=False)
31
- return filename
32
-
 
 
 
 
 
 
1
  import pandas as pd
2
+ import traceback
 
 
 
3
 
4
  def run_code(file, code):
5
  scope = {'pd': pd}
6
  if file:
7
+ print('file ok')
8
+ df = pd.read_excel(file)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ scope['df'] = df
11
+ try:
12
+ # Attempt to execute the user's code
13
+ exec(code, scope, scope)
14
+ except Exception as e:
15
+ # Catch any exceptions that occur and print the error message
16
+ error_msg = traceback.format_exc()
17
+ print(f"Error executing user code: {error_msg}")
18
+ scope['new_df'] = df # Use the original df if error occurs
19
+ return scope['new_df'], error_msg # Return the error message along with the df
20
 
21
+ print(scope.keys())
22
+ if 'new_df' not in scope:
23
+ print("new_df not defined")
24
+ scope['new_df'] = df.copy()
25
+ new_df = scope['new_df']
26
+
27
+ return new_df, None # Return None as the error message when execution is successful
28
+ else:
29
+ print("No file provided")
30
+ return pd.DataFrame(), "No file provided"