MapInfo Pro Developers User Group

 View Only

Redirecting Python interpreter errors to MapInfo output

  • 1.  Redirecting Python interpreter errors to MapInfo output

    Posted 09-26-2023 07:26

    Hi,

    I'm writing a python addin to load in custom UI elements (tabs, groups, controls, etc) by interpreting a JSON file. Currently the way the addin links functionality to controls is by using the commonutils.do() method on a path specified in the JSON file. When the control is initialised a container object is created to hold the path and the control's command is associated with the object's call() method.

    Container Class:

    #Small object, holds path to script and calls later on when assigned
    class custCommand():
    
        def __init__(self, path):
            self.path = path
    
        def call(self, sender):
            CommonUtil.do("run application \"{}\"".format(self.path))

    Command Assignment:

    #Check if existing command id was supplied
    if isinstance(control[fConComm], int):
         newControl.CommandId = control[fConComm]
    else:
         #Create new custom command object and append it to custCommands list for dereferencing later on
         self._custCommands.append(custCommand(control[fConComm]))                        
         newControl.Command = AddinUtil.create_command(self._custCommands[-1].call)

    The issue is that when python scripts are run via these controls, any interpreter/compilation errors are not passed through to MapInfo, and simply disappear into the ether.

    Take the following code as an example:

    import csv
    import sys
    #import os
    
    sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "\py_addin_util")
    
    from mi_common_util import CommonUtil
    from MapInfo.Types import MessageOutput
    
    # redirect python stdio to Pro
    sys.stdout = sys.stderr = sys.stdin = MessageOutput()
    
    #Ask user for file path
    path = CommonUtil.eval('FileOpenDlg("", "", ".csv", "Please select the .csv with turbine information")')
    print(path)

    If I try to run this script in MapInfo directly using either the run application command in the mapbasic window or through the tools window GUI element I get a messagebox with the following interpreter error:

    This tells me what the issue is, that I need to ensure that the os module is imported. When this is run through a control however I get nothing. I've tried redirecting the stderr output to the MapInfo.Types.MessageOutput() as was done in the other python code samples provided with MapBasic, but it doesn't seem to make any difference?

    Is there anything I can do to ensure that all errors are captured by the MapInfo Pro error reporting mechanism?



    ------------------------------
    Romano Agostini
    Knowledge Community Shared Account
    ------------------------------