@@ -299,25 +299,29 @@ def _get_code(self,
299
299
return code
300
300
301
301
302
- def _exec_code (code : str , df_input ):
303
- globals_ = {'df_input' : df_input }
302
+ @lru_cache (maxsize = 64 , typed = True )
303
+ def _get_func_from_code (code : str ):
304
+ globals_ = {}
304
305
exec (code , globals_ )
305
- return globals_ ['df_output ' ]
306
+ return globals_ ['main ' ]
306
307
307
308
308
- def _exec_file (file , df_input ):
309
- file = pathlib .Path (file )
310
- logger .info (f'run file "{ file .absolute ()} "' )
311
- with open (file , 'r' , encoding = 'utf-8' ) as f :
312
- code = f .read ()
313
- return _exec_code (code , df_input )
314
-
315
-
316
- def _exec_module (module : str , df_input ):
309
+ @lru_cache (maxsize = 64 , typed = True )
310
+ def _get_func_from_module (module : str ):
317
311
""""可下断点调试"""
318
312
m = __import__ (module , fromlist = ['*' ])
319
313
logger .info (f'run module { m } ' )
320
- return m .main (df_input )
314
+ return m .main
315
+
316
+
317
+ @lru_cache (maxsize = 64 , typed = True )
318
+ def _get_func_from_file (file : str ):
319
+ file = pathlib .Path (file )
320
+ logger .info (f'run file "{ file .absolute ()} "' )
321
+ with open (file , 'r' , encoding = 'utf-8' ) as f :
322
+ globals_ = {}
323
+ exec (f .read (), globals_ )
324
+ return globals_ ['main' ]
321
325
322
326
323
327
_TOOL_ = ExprTool ()
@@ -347,7 +351,7 @@ def codegen_exec(df: Optional[DataFrame],
347
351
output_file: str| TextIOBase
348
352
保存生成的目标代码到文件中
349
353
run_file: bool or str
350
- 是否不生成脚本,直接运行代码。
354
+ 是否不生成脚本,直接运行代码。注意:带缓存功能,多次调用不重复生成
351
355
- 如果是True,会自动从output_file中读取代码
352
356
- 如果是字符串,会自动从run_file中读取代码
353
357
- 如果是模块名,会自动从模块中读取代码(可调试)
@@ -378,13 +382,13 @@ def codegen_exec(df: Optional[DataFrame],
378
382
if df is not None :
379
383
if run_file is True :
380
384
assert output_file is not None , 'output_file is required'
381
- return _exec_file (output_file , df )
385
+ return _get_func_from_file (output_file )( df )
382
386
if run_file is not False :
383
387
run_file = str (run_file )
384
388
if run_file .endswith ('.py' ):
385
- return _exec_file (run_file , df )
389
+ return _get_func_from_file (run_file )( df )
386
390
else :
387
- return _exec_module (run_file , df ) # 可断点调试
391
+ return _get_func_from_module (run_file )( df ) # 可断点调试
388
392
389
393
# 此代码来自于sympy.var
390
394
frame = inspect .currentframe ().f_back
@@ -407,4 +411,4 @@ def codegen_exec(df: Optional[DataFrame],
407
411
if df is None :
408
412
return None
409
413
else :
410
- return _exec_code (code , df )
414
+ return _get_func_from_code (code )( df )
0 commit comments