Recently in a project, the development environment uses QT C + +. Using Amazon Cloud services in the project, the survey found an Amazon cloud Python interface. With the problem in the title, you need to use C + + to invoke the Python script.
Here is a small example of a C + + call to Python. I post the code first and then in detail.
# -*-coding:cp936-*- # define the Hello function, the function of which is to output "Hello world!" def Hello (): Print ("Hello world! ")
That's why we're going to call the Python script in C + +, you see, there are only two lines, and that's the reason why we call the Amazon Cloud's Python interface.
#include <QCoreApplication>#include<Python.h>#include<iostream>using namespacestd;intMainintargcChar*argv[]) {Qcoreapplication A (argc, argv); //initializing the Python modulepy_initialize (); if( !py_isinitialized ()) { return-1; } //Import test.py Modulepyobject* Pmodule = Pyimport_importmodule ("Test"); if(!pmodule) {printf ("Cant Open python file!\n"); return-1; } //get the Hello function in the test modulepyobject* pfunhello= pyobject_getattrstring (Pmodule,"Hello"); //The commented out part is another way to get the Hello function in the test module//pyobject* pdict = pymodule_getdict (pmodule);//if (!pdict) {//printf ("Cant find dictionary.\n");//return-1;// }//pyobject* Pfunhello = pydict_getitemstring (pdict, "Hello"); if(!Pfunhello) {cout<<"Get function Hello failed"<<Endl; return-1; } //Call the Hello functionpyobject_callfunction (pfunhello,null); //end, release pythonpy_finalize (); returna.exec ();}
Above is the code for C + + calling Python. To learn more about these py** functions, you can go to Python manuals or other web resources, and I'm looking at this http://segmentfault.com/a/1190000000531613
The structure of this test project is as follows:
Before running it needs to be configured, notice that main.cpp contains a Python.h header file, which is required to invoke the Python script, and we also configure the project's. Pro file to include Python's include and Lib.
The configuration is as follows:
Does this make it possible to invoke the Python code?
Take a look at our running results:
As you can see, there is no Python file open, why?
This is because the generated EXE file and the tests.py file are not in the same folder, as long as the manual copy test.py to the exe file sibling directory.
And then we'll try it again:
It worked!
This is where the problem is, welcome to the point.
Using C + + to call Python in QT