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/, and the python code is /my/dir/ contains the following (simplified) lines:

    // Add /my/dir/ - full path to - to python module search path
    PyRun_SimpleString("import sys\nsys.path.append('/my/dir')");
    // Generate name for module:
    PyObject * file = PyString_FromString("bar");
    // Import Python module bar:
    PyObject * module = PyImport_Import(file);

    The application builds and runs successfully as long as is located in /my/dir/.

    The question is: how to include the python file into the installation package?

    Copying to the destination directory is not an option because it will be readable by users.

    I tried to make the application resource:


    RESOURCES = foo.qrc

    In foo.qrc:


    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.

  • Qt Champions 2018

    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.

  • Lifetime Qt Champion


    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!

  • Lifetime Qt Champion

    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 :)

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.