How to reinitialise an embedded Python interpreter?

前端 未结 3 1084
一向
一向 2021-02-04 13:06

I\'m working on embedding Python in our test suite application. The purpose is to use Python to run several tests scripts to collect data and make a report of tests. Multiple te

3条回答
  •  伪装坚强ぢ
    2021-02-04 13:43

    Here is another way I found to achieve what I want, start with a clean slate in the interpreter.

    I can control the global and local namespaces I use to execute the code:

    // get the dictionary from the main module
    // Get pointer to main module of python script
    object main_module = import("__main__");
    // Get dictionary of main module (contains all variables and stuff)
    object main_namespace = main_module.attr("__dict__");
    
    // define the dictionaries to use in the interpreter
    dict global_namespace;
    dict local_namespace;
    
    // add the builtins
    global_namespace["__builtins__"] = main_namespace["__builtins__"];
    

    I can then use use the namespaces for execution of code contained in pyCode:

    exec( pyCode, global_namespace, lobaca_namespace );
    

    I can clean the namespaces when I want to run a new instance of my test, by cleaning the dictionaries:

    // empty the interpreters namespaces
    global_namespace.clear();
    local_namespace.clear();        
    
    // Copy builtins to new global namespace
    global_namespace["__builtins__"] = main_namespace["__builtins__"];
    

    Depending at what level I want the execution, I can use global = local

提交回复
热议问题