1

Simple example from docs not working for me (Failed to load "test.py"). I try what other people say: ask ask2

All not working! code:

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

build file (sconstruct):

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'])

All on ubuntu 13.04 64bit. result from terminal:

$ ./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

all files in one directory with test.py file. Please Help.

2
  • "Not working for me" does mean exactly what? What phenomenon do you encounter? Please elaborate which step results in which unexpected ("not working") behavior. Commented Aug 23, 2013 at 12:30
  • result - Failed to load "test.py" Commented Aug 28, 2013 at 7:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.