1.被执行的脚本
2.主程序
3.源码加载
4.执行demo
5.执行结果
6.源码:
def init(): print('helloWorld!')
import codecs from six import exec_ class CodeLoader: def __init__(self, strategyfile): self._strategyfile = strategyfile def compile_strategy(self, source_code, strategyfile, scope): code = compile(source_code, strategyfile, 'exec') exec_(code, scope) return scope # def load(self, scope): with codecs.open(self._strategyfile, encoding="utf-8") as f: source_code = f.read() return self.compile_strategy(source_code, self._strategyfile, scope)
# -*- coding: utf-8 -*- from CodeLoader import CodeLoader def run_file(strategy_file_path): loader = CodeLoader(strategy_file_path) scope = {} scope = loader.load(scope) f = scope.get('init', None) f()
# -*- coding: utf-8 -*- from main import run_file file_path = "./file.py" run_file(file_path)