嵌入式Python 2.7.2从用户定义的目录导入模块 [英] Embedded Python 2.7.2 Importing a module from a user-defined directory

查看:73
本文介绍了嵌入式Python 2.7.2从用户定义的目录导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Python嵌入到具有已定义API的C/C ++应用程序中.

I'm embedding Python into a C/C++ application that will have a defined API.

应用程序需要实例化脚本中定义的类,这些类的结构大致如下:

The application needs to instantiate classes defined in a script, which are structured roughly like this:

class userscript1:
    def __init__(self):
        ##do something here...

    def method1(self):
        ## method that can be called by the C/C++ app...etc

我过去曾为(概念验证)设法使用以下类型的代码来完成此任务:

I've managed in the past (for the proof-of-concept) to get this done using the following type of code:

PyObject* pName = PyString_FromString("userscript.py");
PyObject* pModule = PyImport_Import(pName);
PyObject* pDict = PyModule_GetDict(pModule);
PyObject* pClass = PyDict_GetItemString(pDict, "userscript");
PyObject* scriptHandle = PyObject_CallObject(pClass, NULL);

现在我更多地处于生产环境中,这在PyImport_Import行上失败了-我认为这可能是因为我试图在目录前添加脚本名称,例如

Now that I'm in more of a production environment, this is failing at the PyImport_Import line - I think this might be because I'm trying to prepend a directory to the script name, e.g.

PyObject* pName = PyString_FromString("E:\\scriptlocation\\userscript.py");

现在,为了让您了解我已经尝试过的方法,我尝试在所有这些调用之前修改系统路径,以使其搜索此模块.基本上尝试以编程方式修改sys.path:

Now, to give you an idea of what I've tried, I tried modifying the system path before all of these calls to make it search for this module. Basically tried modifying sys.path programmatically:

PyObject* sysPath = PySys_GetObject("path");
PyObject* path = PyString_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);

这些行运行正常,但对使我的代码正常工作没有任何作用.显然,我的实际代码中有很多错误检查已排除在外,所以不必担心!

These lines run ok, but have no effect on making my code work. Obviously, my real code has a boatload of error checking that I have excluded so don't worry about that!

所以我的问题是:如何将嵌入式解释器适当地定向到我的脚本,以便实例化这些类?

So my question: how do I direct the embedded interpreter to my scripts appropriately so that I can instantiate the classes?

推荐答案

您需要指定userscript,而不是userscript.py也要使用PyImport_ImportModule,它直接需要char *

you need to specify userscript and not userscript.py also use PyImport_ImportModule it directly takes a char *

userscript.py表示软件包userscript

此代码对我有用:

#include <stdio.h>
#include <stdlib.h>
#include <Python.h>

int main(void)
{
    const char *scriptDirectoryName = "/tmp";
    Py_Initialize();
    PyObject *sysPath = PySys_GetObject("path");
    PyObject *path = PyString_FromString(scriptDirectoryName);
    int result = PyList_Insert(sysPath, 0, path);
    PyObject *pModule = PyImport_ImportModule("userscript");
    if (PyErr_Occurred())
        PyErr_Print();
    printf("%p\n", pModule);
    Py_Finalize();
    return 0;
}

这篇关于嵌入式Python 2.7.2从用户定义的目录导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆