I installed Python
3.8.5 + modules tkinter
and OpenCV
.
There’s lots of posts saying cv2
or tkinter
fails to load, it works perfectly on my system. This script…
print("Importing tkinter")
import tkinter
print("Imported tkinter")
print("Importing cv2")
import cv2
print("Imported cv2")
print('Hello World from Python!')
…works just fine. C:/Python385/python.exe C:/dev/example.py
outputs:
Importing tkinter
Imported tkinter
Importing cv2
Imported cv2
Hello World from Python!
Now I want to execute this script from a C++
program:
#include <iostream>
#include <sstream>
#include <boost/filesystem.hpp>
#include <Python.h>
int main(int argc, char **argv)
{
#define PYTHONDEFAULTHOMEDIR "C:/Python385"
#define PYTHON_FILE "C:/dev/example.py"
std::wstringstream str;
str << PYTHONDEFAULTHOMEDIR;
Py_SetPythonHome( str.str().c_str() );
// Initialize the Python Interpreter
Py_Initialize();
std::string filePath = PYTHON_FILE;
int res = 0;
FILE* file = NULL;
fopen_s(&file,filePath.c_str(),"r");
if ( file )
{
res = PyRun_SimpleFile(file, filePath.c_str());
fclose(file);
std::cout << "Result = " << res << std::endl;
}
else
{
std::cout << "Unable to open example.py file" << std::endl;
res = 1;
}
Py_Finalize();
return res;
}
I’m using Visual Studio 2022
.
In Debug
, I get the error:
Importing tkinter
Traceback (most recent call last):
File "C:/dev/vobs_sde/private/sdetests/prg/sdetests_3p_python/data/python/example.py", line 2, in <module>
import tkinter
File "C:devcalipsoPython385libtkinter__init__.py", line 36, in <module>
import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'
Result = -1
I found posts saying this is because tkinter
module is provided in Release
not in Debug
so it fails to load from a Debug
program. So I switch to Release
builds.
In Release
, I get the error:
Importing tkinter
Imported tkinter
Importing cv2
Traceback (most recent call last):
File "C:/dev/vobs_sde/private/sdetests/prg/sdetests_3p_python/data/python/example.py", line 6, in <module>
import cv2
File "C:devcalipsoPython385libsite-packagescv2__init__.py", line 181, in <module>
bootstrap()
File "C:devcalipsoPython385libsite-packagescv2__init__.py", line 153, in bootstrap
native_module = importlib.import_module("cv2")
File "C:devcalipsoPython385libimportlib__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ImportError: DLL load failed while importing cv2: Le module spécifié est introuvable.
Result = -1
So now tkinter
can be loaded but not OpenCV
. Is there anything special to be done in order to load OpenCV
from a Python
script executed from C++
?