小编kov*_*csv的帖子

在嵌入式 Python 中禁用内置模块导入

我在我的应用程序中嵌入了 Python 3.6,我想在脚本中禁用导入命令以防止用户导入任何 Python 内置库。我只想使用语言本身和我自己的 C++ 定义的模块。

Py_SetProgramName (L"Example");
Py_Initialize ();
PyObject* mainModule = PyImport_AddModule ("__main__");
PyObject* globals = PyModule_GetDict (mainModule);

// This should work
std::string script1 = "print ('example')";
PyRun_String (script1.c_str (), Py_file_input, globals, nullptr);

// This should not work
std::string script2 = "import random\n"
                      "print (random.randint (1, 10))\n";
PyRun_String (script2.c_str (), Py_file_input, globals, nullptr);

Py_Finalize ();
Run Code Online (Sandbox Code Playgroud)

你知道有什么方法可以实现这一目标吗?

c++ python python-embedding python-3.x

5
推荐指数
1
解决办法
1290
查看次数

标签 统计

c++ ×1

python ×1

python-3.x ×1

python-embedding ×1