Solved How to deploy Qt application with embedded Python?
-
Hello,
My Qt application is in C++, and calls the embedded python API. Suppose the application source code is /my/dir/foo.cc, and the python code is /my/dir/bar.py.
foo.cc contains the following (simplified) lines:
// Add /my/dir/ - full path to bar.py - to python module search path PyRun_SimpleString("import sys\nsys.path.append('/my/dir')"); // Generate name for bar.py module: PyObject * file = PyString_FromString("bar"); // Import Python module bar: PyObject * module = PyImport_Import(file);
The application builds and runs successfully as long as bar.py is located in /my/dir/.
The question is: how to include the python file into the installation package?
Copying bar.py to the destination directory is not an option because it will be readable by users.
I tried to make bar.py the application resource:
In foo.pro:
RESOURCES = foo.qrc
In foo.qrc:
<qresource> <file>bar.py</file> </qresource>
And instead of adding /my/dir to sys.path, I added /full/path/to/binary (i.e destination directory).
The method did not work - PyImport_Import() could not find the bar module.
Any suggestions - either on how to make the "resource" approach work, or an alternative approach - will be greatly appreciated.
-
Do I understand you right: you don't want your users to be able to read the Python code?
Embedding the Python code into your executable will not help in this case: user can just view your executable in an hex-editor or extract strings from it.
I can only think of two solutions:- Obfuscate the Python code and put it in installation directory
- Encrypt Python code
-
Thank you for the prompt response, @jsulm! Yes, the python code can be extracted from the executable, but this is not a big concern. Everything can be reverse-engineered... I do not want the .py files sitting in the directory, where everybody can easily access them. But if it is possible to embed them into the executable, this will be good enough for me.
-
Hi,
The most simple solution that comes to mind is to copy the file from the resource to the hard drive using e.g. a QTemporaryFile or put it in an adequate folder provided by QStandardPaths. Then you can setup your python path properly.
Hope it helps
-
Thank you, @SGaist, this is a good solution!
-
You're welcome !
If that answers your question, then please mark the thread as solved using the "Topic Tool" button so that other forum users may know a solution has been found :)