1.被执行的脚本

Python执行指定文件的方法

2.主程序

Python执行指定文件的方法

3.源码加载

Python执行指定文件的方法

4.执行demo

Python执行指定文件的方法

5.执行结果

Python执行指定文件的方法

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)

相关文章:

  • 2022-12-23
  • 2021-11-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-08
  • 2022-01-11
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-18
  • 2021-10-10
  • 2021-09-18
相关资源
相似解决方案