Why does the Python/C API crash on PyRun_SimpleFile?

后端 未结 7 696
一整个雨季
一整个雨季 2020-12-15 07:45

I\'ve been experimenting with embedding different scripting languages in a C++ application, currently I\'m trying Stackless Python 3.1. I\'ve tried several tutorials and exa

相关标签:
7条回答
  • 2020-12-15 08:09

    Your code works correctly on my installed version of Python 2.6. I also built stackless 3.1.2 from source and it worked correctly. This was with g++ 4.4.3 on Ubuntu 10.04. If you're on windows, you might want to check that both stackless and your code are built against the same C runtime.

    0 讨论(0)
  • 2020-12-15 08:11

    I was getting a similar crash & did the below:

       PyObject* PyFileObject = PyFile_FromString("test.py", "r");
       PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "test.py", 1);
    

    Note that this was in python 2.7 though. I don't know if the API has changed in 3.x.

    0 讨论(0)
  • 2020-12-15 08:15

    This works for me on Python 3:

     PyObject *obj = Py_BuildValue("s", "test.py");
     FILE *file = _Py_fopen_obj(obj, "r+");
     if(file != NULL) {
         PyRun_SimpleFile(file, "test.py");
     }
    

    I hope It would be useful.

    0 讨论(0)
  • 2020-12-15 08:20

    And what about this solution:

    Py_SetProgramName(argv[0]);
    Py_Initialize();
    PyRun_SimpleString("execfile(\"ex30.py\")");
    Py_Finalize();
    

    Where ex30.py it the name of the python script I am running.

    0 讨论(0)
  • 2020-12-15 08:22

    The below code will execute the test.py module. Python will search the module in the path set. So the path should be handled first.

    Py_Initialize();
    
    string path = "Python Scripts/";
    
    //Set the path
    PyRun_SimpleString("import sys");
    string str = "sys.path.append('" + path + "')";
    PyRun_SimpleString(str.c_str());
    
    //Dont use test.py as it actually searches sub module test>>py
    PyObject * moduleName = PyUnicode_FromString("test");
    PyObject * pluginModule = PyImport_Import(moduleName);
    
    if (pluginModule == nullptr)
    {
        PyErr_Print();
        return "";
    }
    
    //Do the executions here
    
    //clean up
    Py_DECREF(moduleName);
    Py_DECREF(pluginModule);
    Py_DECREF(transformFunc);
    Py_DECREF(result);
    
    Py_Finalize();
    
    0 讨论(0)
  • 2020-12-15 08:33

    If you built your test with VC 2010, you will definitely have problems - VC9 (VS 2008) and VC10 (VS 2010) have mutually incompatible support DLLs that are usually required (implement printf, file i/o and that sort of thing). You cannot mix them if they include the standard libraries, which the python build does.

    You always have the option of using gcc (e.g. Cygwin or mingw) or downloading Visual Studio 2008 express, which should work fine for experimentation into python embedding. I have used both with the standard Python 2.7.6 build.

    0 讨论(0)
提交回复
热议问题