如何在另一个 python 函数中执行一个 python 文件?

How to execute a python file in another python function?

我正在尝试编写一个可用于执行其他 python 文件的函数...

预期的行为应该是,使用该函数导入其他模块,以便导入这些模块应该自动执行脚本。

下面的函数是我写的

fp_a = 'C:..../'  # file path to each python file
results= []
def running(script,filepath):
    try:
        start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print(start_time)
        sys.path.insert(0,filepath)
        import script
        results.append('%s Completed Started at'+ start_time +' Ended at ' + end_time %(script))
        end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print(end_time)
    except:
        results.append('Salary Failed')

running('fx_rates',fp_a)

我实际上能够通过使用 importlib 模块解决这个问题

import datetime,sys,os
sys.path.insert(0,'some path')
import importlib as ip
results= []
def execution(fp, file):
    sys.path.insert(0,fp)
    start_time = now(2)
    im = ip.import_module(file)
    end_time = now(2)
    try:
        if  not im.error:
            results.append(file+' Job Completed! Started at '+ start_time +' Ended at ' + end_time)
            print(file+' Job Completed! Started at  '+ start_time +' Ended at ' + end_time )
        else:
            results.append(file+' Job Failed! Started at '+ start_time +' Failed at ' + end_time + ' The error was: '+ str(im.error))
            print(file+' Job Failed! Started at '+ start_time +' Failed at ' + end_time + ' The error was: '+ str(im.error))
    except:
            results.append(file+' Job Completed! Started at '+ start_time +' Ended at ' + end_time)
            print(file+' Job Completed! Started at  '+ start_time +' Ended at ' + end_time )