Main Content

Generate Python Package and Build Python Application

Supported platforms: Windows®, Linux®, Mac

This example shows how to create a Python® package from a MATLAB® function and integrate the package into a Python application generated with MATLAB Compiler SDK™.

Prerequisites

Verify that you have met the system requirements for generating Python packages and running Python applications. For details, see MATLAB Compiler SDK Python Target Requirements.

Create Function in MATLAB

In MATLAB, examine the MATLAB code that you want to use in your Python application. For this example, create a function named makesqr.m that contains the following code:

function y = makesqr(x)
y = magic(x);

At the MATLAB command prompt, enter makesqr(5).

The output is a 5-by-5 matrix.

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

Create Python Package Using compiler.build.pythonPackage

Build a Python package using a programmatic approach. Alternatively, if you want to create a Python package using a graphical interface, see Create Python Application Using Library Compiler App.

  1. Create a MATLAB sample script that calls your function. Save the following code in a sample file named makesqrSample1.m.

    % Sample script to demonstrate execution of function y = makesqr(x)
    x = 5;
    y = makesqr(x);

    During packaging, MATLAB Compiler SDK uses the sample MATLAB script to generate a sample application in the target language. For more information, see Create Sample Code to Call Exported Function.

  2. Build the Python package using the compiler.build.pythonPackage function and the makesqr.m file that you created earlier. Use name-value arguments to specify the package name and add the sample file. You can specify additional options in the compiler.build command by using name-value arguments. For details, see compiler.build.pythonPackage.

    buildResults = compiler.build.pythonPackage('makesqr.m', ...
        'PackageName','MagicSquarePkg', ...
        'SampleGenerationFiles','makesqrSample1.m', ...
        'Verbose','on');

    The compiler.build.Results object buildResults contains information on the build type, generated files, included support packages, and build options.

  3. The function generates the following files within a folder named MagicSquarePkgpythonPackage in your current working directory:

    • samples\makesqrSample1.py — Python sample application file.

    • MagicSquarePkg\__init__.py — Python initialization code that facilitates importing your package.

    • MagicSquarePkg\MagicSquarePkg.ctf — Deployable archive that contains your Python package.

    • GettingStarted.html — HTML file that contains information on integrating your package.

    • includedSupportPackages.txt — Text file that lists all support files included in the package.

    • mccExcludedFiles.log — Log file that contains a list of any toolbox functions that were not included in the application. For information on non-supported functions, see MATLAB Compiler Limitations.

    • pyproject.toml — Configuration file that contains build system requirements and information, which are used by pip to build the package. For details, see pip.pypa.io/en/stable/reference/build-system/pyproject-toml.

    • readme.txt — Text file that contains packaging and interface information.

    • requiredMCRProducts.txt — Text file that contains product IDs of products required by MATLAB Runtime to run the application.

    • setup.py — Python file that installs the package.

    • unresolvedSymbols.txt — Text file that contains information on unresolved symbols.

    Note

    The generated package does not include MATLAB Runtime or an installer. To create an installer using the buildResults object, see compiler.package.installer.

Install and Run MATLAB Generated Python Application

After creating your Python package, you can call it from a Python application. This example uses the sample Python code generated during packaging. You can use this sample Python application code as a guide to write your own application.

  1. At the system command prompt, navigate to the MagicSquarePkgpythonPackage folder.

  2. Install the application using the python command.

    python -m pip install .

    For more information on installing Python packages, see Install and Import MATLAB Compiler SDK Python Packages.

  3. After installing the package, navigate to the samples folder that contains makesqrSample1.py.

    The contents of makesqrSample1.py are shown below.

    #!/usr/bin/env python
    """
    Sample script that uses the MagicSquarePkg package created using
    MATLAB Compiler SDK.
    
    Refer to the MATLAB Compiler SDK documentation for more information.
    """
    
    import MagicSquarePkg
    # Import the matlab module only after you have imported 
    # MATLAB Compiler SDK generated Python modules.
    import matlab
    
    try:
        my_MagicSquarePkg = MagicSquarePkg.initialize()
    except Exception as e:
        print('Error initializing MagicSquarePkg package\\n:{}'.format(e))
        exit(1)
    
    try:
        xIn = matlab.double([5], size=(1, 1))
        yOut = my_MagicSquarePkg.makesqr(xIn)
        print(yOut, sep='\\n')
    except Exception as e:
        print('Error occurred during program execution\\n:{}'.format(e))
    
    my_MagicSquarePkg.terminate()

    The Python sample application does the following:

    • Imports the MagicSquarePkg package

    • Imports the matlab package

    • Uses a try-catch block to handle exceptions

    • Initializes a MagicSquarePkg object named my_MagicSquarePkg

    • Creates matlab.double object that contains the input argument xIn

    • Calls the makesqr method and saves the output to yOut

    • Prints the contents of yOut

    • Terminates the my_MagicSquarePkg instance

  4. If you have installed MATLAB Runtime, you can run the application at the system command prompt. For testing purposes, you can also run the command in the MATLAB Command Window by preceding the command with the ! operator.

    python makesqrSample1.py

    The Python sample application returns the same output as the sample MATLAB script.

    [[17.0,24.0,1.0,8.0,15.0],[23.0,5.0,7.0,14.0,16.0],[4.0,6.0,13.0,20.0,22.0],
    [10.0,12.0,19.0,21.0,3.0],[11.0,18.0,25.0,2.0,9.0]]

    Note

    On macOS, you must use the mwpython script instead of python. For example, mwpython makesqrSample1.py.

    The mwpython script is located in the matlabroot/bin folder, where matlabroot is the location of your MATLAB or MATLAB Runtime installation.

See Also

| | | |

Related Topics