Main Content

Create Python Application Using Library Compiler App

This example shows how to use the Library Compiler app in MATLAB® Compiler SDK™ to package a MATLAB function into a Python® package. Alternatively, if you want to create a Python package from the MATLAB Command Window using a programmatic approach, see Generate Python Package and Build Python Application.

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

Create Python Package Using Library Compiler

  1. On the MATLAB Apps tab, on the far right of the Apps section, click the arrow. In Application Deployment, click Library Compiler.

    Alternately, you can open the Library Compiler app by entering libraryCompiler at the MATLAB prompt.

  2. Library Compiler app toolstrip, with function makesqr.m and application name MagicSquarePkg

    1. In the Type section of the toolstrip, click Python Package.

    2. In the Exported Functions section of the toolstrip, specify the files of the MATLAB application that you want to deploy.

      For this example, select the makesqr.m file that you wrote earlier.

    3. In the Packaging Options section of the toolstrip, decide whether to include the MATLAB Runtime installer in the generated application by selecting one of the options:

      • Runtime downloaded from web — Generate an installer that downloads the MATLAB Runtime and installs it along with the deployed MATLAB application. You can specify the file name of the installer.

      • Runtime included in package — Generate an application that includes the MATLAB Runtime installer. You can specify the file name of the installer.

      Note

      The first time you select this option, you are prompted to download the MATLAB Runtime installer.

  3. Next, choose a name for your Python package. The Library Name field is automatically populated with makesqr as the name of the package. Rename it as MagicSquarePkg. For more information on naming requirements for the Python package, see Install and Import MATLAB Compiler SDK Python Packages.

  4. Create Sample File

    During packaging, MATLAB Compiler SDK can generate Python code that demonstrates how to call your MATLAB exported function. To generate Python code, create MATLAB sample files and add them to the project. The compiler converts this MATLAB code to Python code during packaging. For more information and limitations, see Create Sample Code to Call Exported Function.

    To generate a new MATLAB sample file, click Create New Sample and select your MATLAB function. This opens up a MATLAB script for you to edit. The generated sample script calls your MATLAB function with arguments set to zero, which you should modify as necessary based on the intended behavior of your function.

    Change x = 0 to x = 5, save the file, and return to the Library Compiler app.

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

    Caution

    You must edit the MATLAB sample file to output your desired result. Generated target language code uses the same inputs and outputs as the sample MATLAB file.

  5. Customize the packaged application and its appearance:

    In the Library Compiler app, you can customize the installer, customize your application, and add more information about the application.

    • Library information — Information about the deployed application. You can also customize the appearance of the application by changing the application icon and splash screen. The generated installer uses this information to populate the installed application metadata. See Customize the Installer.

    • Additional installer options — Default installation path for the generated installer and custom logo selection. See Change the Installation Path.

    • Files required for your library to run — Additional files required by the generated application to run. These files are included in the generated application installer. See Manage Required Files in Compiler Project.

    • Files installed for your end user — Files that are installed with your application. See Specify Files to Install with Application.

    Library Compiler app with a sample file named makesqrSample1.m.

  6. Package the Application

    When you are finished selecting your packaging options, save your Library Compiler project and generate the packaged application.

    1. Click Package. In the Save Project dialog box, specify the location to save the project.

    2. In the Package dialog box, verify that Open output folder when process completes is selected. When the packaging process is complete, examine the generated output in the target folder.

    • Three folders are generated: for_redistribution, for_redistribution_files_only, and for_testing. For more information about the files generated in these folders, see Files Generated After Packaging MATLAB Functions.

    • The log file PackagingLog.html contains packaging results.

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 MagicSquarePkg folder.

  2. Install the application using the generated installer or navigate to the folder that contains setup.py and install the package 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