嵌入式Python 2.7.2:从用户定义的目录导入模块

8

我将Python嵌入到一个有定义API的C/C++应用程序中。

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

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

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

过去我曾经(用于概念验证)使用以下类型的代码来完成这个任务:

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行失败了 - 我认为这可能是因为我试图将一个目录添加到脚本名之前,例如:

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

现在,为了让您了解我尝试过什么,我尝试在所有这些调用之前修改系统路径,使其搜索此模块。基本上是通过编程方式修改sys.path:
PyObject* sysPath = PySys_GetObject("path");
PyObject* path = PyString_FromString(scriptDirectoryName);
int result = PyList_Insert(sysPath, 0, path);

这些代码段没有问题,但并没有对我的代码起到任何作用。显然,我的真实代码中有大量的错误检查被排除在外,所以不用担心!
那么我的问题是:我该如何正确地将嵌入式解释器指向我的脚本,以便我可以实例化这些类?
1个回答

18

你需要指定userscript而不是userscript.py,并使用PyImport_ImportModule。它直接接受char *参数。

userscript.py 意味着包userscript中的模块py

这段代码对我有效:

#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;
}

1
非常感谢 - 这让我突破了难关!现在要找出我调用的测试脚本有什么问题! - Fritz
2
在Python 3中,PyString_FromString已经被移除。请使用PyBytes_FromString代替。 - edj
1
PySys_GetObject("path"); 中的 path 是什么作用?为什么需要它? - sAguinaga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接