嵌入python 3示例不起作用

时间:2013-08-23 11:29:01

标签: c++ python importerror embedding

文档无效的简单示例 对我来说(无法加载" test.py")。我尝试别人说的话: ask ask2

一切都行不通! 码:

#include <Python.h>

#include <fstream>
#include <iostream>
#include <string>

int
main(int argc, char *argv[])
{
    wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
    for (int i = 0; i < argc; ++i)
    {
        size_t argsize = mbstowcs(NULL, argv[i], 0);
        size_t count;
        if (argsize == (size_t) -1)
        {
            fprintf(stderr, "Could not convert argument %d to string\n", i);
            return 1;
        }
        argv_copy[i] = (wchar_t *) PyMem_Malloc(
                (argsize + 1) * sizeof(wchar_t));
        if (!argv_copy[i])
        {
            fprintf(stderr, "out of memory\n");
            return 1;
        }
        count = mbstowcs(argv_copy[i], argv[i], argsize + 1);
        if (count == (size_t) -1)
        {
            fprintf(stderr, "Could not convert argument %d to string\n", i);
            return 1;
        }
    }

    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_SetProgramName(argv_copy[0]);  /* optional but recommended */
    Py_Initialize();
    PySys_SetArgv(argc, argv_copy); // must call this to get sys.argv and relative imports

    PyRun_SimpleString("import os, sys");
    PyRun_SimpleString("sys.path.append(os.getcwd())");

    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");

    PyRun_SimpleString("import os, sys\n"
                       "print(\"sys.argv:\", sys.argv)\n"
                       "print(\"cwd:\", os.getcwd())\n"
                       "print(\"sys.path:\", sys.path)\n"
            );

    pName = PyUnicode_FromString(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyLong_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyLong_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);

        std::ifstream ifs;
        ifs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
        ifs.open(argv[1]);
        while (ifs.good() && !ifs.eof())
        {
            std::string line;
            std::getline(ifs, line);
            std::cout << line << "\n";
        }

        return 1;
    }
    Py_Finalize();
    return 0;
}

#include <Python.h> #include <fstream> #include <iostream> #include <string> int main(int argc, char *argv[]) { wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc); for (int i = 0; i < argc; ++i) { size_t argsize = mbstowcs(NULL, argv[i], 0); size_t count; if (argsize == (size_t) -1) { fprintf(stderr, "Could not convert argument %d to string\n", i); return 1; } argv_copy[i] = (wchar_t *) PyMem_Malloc( (argsize + 1) * sizeof(wchar_t)); if (!argv_copy[i]) { fprintf(stderr, "out of memory\n"); return 1; } count = mbstowcs(argv_copy[i], argv[i], argsize + 1); if (count == (size_t) -1) { fprintf(stderr, "Could not convert argument %d to string\n", i); return 1; } } PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; int i; if (argc < 3) { fprintf(stderr,"Usage: call pythonfile funcname [args]\n"); return 1; } Py_SetProgramName(argv_copy[0]); /* optional but recommended */ Py_Initialize(); PySys_SetArgv(argc, argv_copy); // must call this to get sys.argv and relative imports PyRun_SimpleString("import os, sys"); PyRun_SimpleString("sys.path.append(os.getcwd())"); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\".\")"); PyRun_SimpleString("import os, sys\n" "print(\"sys.argv:\", sys.argv)\n" "print(\"cwd:\", os.getcwd())\n" "print(\"sys.path:\", sys.path)\n" ); pName = PyUnicode_FromString(argv[1]); /* Error checking of pName left out */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, argv[2]); /* pFunc is a new reference */ if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New(argc - 3); for (i = 0; i < argc - 3; ++i) { pValue = PyLong_FromLong(atoi(argv[i + 3])); if (!pValue) { Py_DECREF(pArgs); Py_DECREF(pModule); fprintf(stderr, "Cannot convert argument\n"); return 1; } /* pValue reference stolen here: */ PyTuple_SetItem(pArgs, i, pValue); } pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { printf("Result of call: %ld\n", PyLong_AsLong(pValue)); Py_DECREF(pValue); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load \"%s\"\n", argv[1]); std::ifstream ifs; ifs.exceptions(std::ifstream::failbit | std::ifstream::badbit); ifs.open(argv[1]); while (ifs.good() && !ifs.eof()) { std::string line; std::getline(ifs, line); std::cout << line << "\n"; } return 1; } Py_Finalize(); return 0; }

构建文件(sconstruct):

全部在ubuntu 13.04 64bit上。 来自终端的结果:

env = Environment()

env.Append(CCFLAGS = ['-I/usr/include/python3.3m'])
env.Append(LIBS = ['pthread', 'dl', 'util', 'm', 'python3.3m'])

env.Program("call", ['python_em_01.cpp'])

使用test.py文件在一个目录中的所有文件。请帮助。

0 个答案:

没有答案