嵌入python3示例不起作用

2024-03-28 11:15:49 发布

您现在位置:Python中文网/ 问答频道 /正文

来自docs not working的简单示例 对我来说(加载失败“测试.py"). 我试试别人说的: askask2

都没用! 代码:

#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):

^{pr2}$

都在ubuntu 13.04 64位上。 来自终端的结果:

$ ./call test.py multiply 3 2
sys.argv: ['./call', 'test.py', 'multiply', '3', '2']
cwd: /home/leo/workspace_kepler/python_em_01
sys.path: ['/home/leo/workspace_kepler/python_em_01', '/usr/local/lib/python3.3/dist-packages/Cython-0.19.1-py3.3-linux-x86_64.egg', '/usr/lib/python3.3', '/usr/lib/python3.3/plat-x86_64-linux-gnu', '/usr/lib/python3.3/lib-dynload', '/usr/local/lib/python3.3/dist-packages', '/usr/lib/python3/dist-packages', '/home/leo/workspace_kepler/python_em_01', '.']
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 1518, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'

During handling of the above exception, another exception occurred:

ImportError: No module named 'test.py'; test is not a package
Failed to load "test.py"
def multiply(a,b):
    print("Will compute", a, "times", b)
    c = 0
    for i in range(0, a):
        c = c + b
    return c

同一目录中的所有文件测试.py文件。请帮忙。


Tags: pyreturniflibstderrsyscopyargv