Python Examples

Following are simple examples demonstrate minimal functioning Python extensions and stand-alone Python program.

Python GX Extensions

Python extensions have a rungx() function.

Hello user extension...

# Oasis montaj Python extension to say Hello.
# To run this extension, select "Settings / Run GX or Python...",
# then browse to this script file.

import geosoft.gxpy as gxpy


# a python script must have a rungx()
def rungx():

    gxpy.utility.check_version('9.2')

    # Get the current gx context
    # This is normally not required but in this example we want the gid.
    with gxpy.gx.GXpy() as gxp:

        # say hello to the user identified by gxp.gid.
        gxpy.utility.display_message("GX Python", "Hello {}".format(gxp.gid))

Add a constant to a channel extension...

'''
Add a constant value to a channel on all selected lines.

This is a sample Python extension that shows how to work with saved parameters
and a Geosoft database.

'''

import geosoft.gxpy as gxpy
import geosoft.gxpy.project as gxprj
import geosoft.gxpy.utility as gxu


def rungx():

    # api version
    gxpy.utility.check_version('9.2')

    # get the current database
    db = gxpy.gdb.Geosoft_gdb.open()

    # project parameters
    group = 'CHANADD'
    p_chan = 'CHANNEL'
    p_addval = 'ADDVAL'

    # get previous parameters from the parameter block, initializing to start-up defaults '' and 0.0
    parms = gxu.get_parameters(group, {p_chan: '', p_addval: 0.0})

    # if interactive, get user input
    if not gxprj.running_script():

        try:
            # get channel to process from list of database channels
            chan = gxprj.get_user_input(
                    'Channel to process',
                    'Channel:',
                    kind='list',
                    default=parms.get(p_chan),
                    items=sorted([k for k in db.list_channels().keys()]))

            # value to add to the channel
            addval = gxprj.get_user_input(
                    'Value to add to the data',
                    'value to add:',
                    kind='float',
                    default=parms.get(p_addval))
        except gxprj.ProjectException:
            exit()

        # save parameters to new user settings
        parms[p_chan] = chan
        parms[p_addval] = addval
        gxu.save_parameters(group, parms)

    # work through the data a line at a time - get a list of selected lines
    lines = db.list_lines()

    # for each line, get the data, add a value, return the data to the line
    for l in lines:

        # print to the console to reflect progress
        print('line {}...'.format(str(l)))

        # get the data and determine the dummy to the data type
        data, ch, fid = db.read_line(l, channels=chan)
        dummy = gxu.gx_dummy(data.dtype)

        # make a dummy mask so we can replace dummies after processing
        dMask = gxu.dummy_mask(data)

        # process - add the value, then replace the dummies
        sum = data + addval
        sum[dMask] = dummy

        # write the data back to the database
        db.write_channel(l, chan, sum, fid)

    # pause the console so user can review
    input("Press return to continue...")

Stand-Alone Python Programs

Stand-alone Python scripts create a GX context before calling any other API functions.

Hello user program...

# This sample stand-alone Python script shows a minimal use of the Pythonic gxpy module to
# create a Geosoft context and say hello to the user.
# This example can be run stand-alon or as a Oasis montaj extension.

import geosoft.gxpy as gxpy   # gxpy methods


# running as an extension from Oasis montaj will execute rungx()
def rungx():

    gxpy.utility.check_version('9.2')

    # say hello
    with gxpy.gx.GXpy() as gxc:
        gxpy.utility.display_message("GX Python", "Hello {}".format(gxc.gid))


# running as stand-alone program
if __name__ == "__main__":

    gxpy.utility.check_version('9.2')

    # Stand-alone programs must create a GX context before calling Geosoft methods.
    with gxpy.gx.GXpy() as gxc:

        # The context has a member 'gid' which contains the user's Geosoft ID.
        # Say hello to the user
        print("Hello {}".format(gxc.gid))

Add a constant to a channel program...

"""
Add a constant value to a channel on all selected lines.

This is a sample Python program that illustrates how to connect to the GX
developer environment from a stand-alone program.

Follwoing are the basic steps:

   1. Get (create) a GX Object handle.
   2. Collect command-line parameters
   3. Open the database
   4. Process the data
"""

import os
import sys
import argparse as argp
import geosoft.gxpy as gxpy

def rungx():
    raise Exception("This is not an extension.  Please use a python interpreter.")

def process_database(db, channel_name, add_value):
    """
    Process all selected lines in a database by adding a constant
    value to a channel. The data is processed in-place.
    """

    # work through the data a line at a time - get a list of selected lines
    print('Processing selected lines...')
    lines = db.list_lines()

    # for each line, get the data, add a value, return the data to the line
    for l in lines:

        # print to the console to reflect progress
        print('line {}...'.format(str(l)))

        # get the data and determine the dummy to the data type
        data, ch, fid = db.read_line(l, channels=channel_name)
        dummy = gxpy.utility.gx_dummy(data.dtype)

        # make a dummy mask so we can replace dummies after processing
        dMask = gxpy.utility.dummy_mask(data)

        # process - add the value, then replace the dummies
        sum = data + add_value
        sum[dMask] = dummy

        # write the data back to the database
        db.write_channel(l, channel_name, sum, fid)


if __name__ == "__main__":

    gxpy.utility.check_version('9.2')

    # get (create) a GX context
    with gxpy.gx.GXpy() as gxp:  # get the current gx context

        # The GX_GEOSOFT_BIN_PATH Environment variable should contain a path with geodist.dll
        print("GX_GEOSOFT_BIN_PATH: {}".format(os.getenv("GX_GEOSOFT_BIN_PATH")))
        print('Working directory: ' + os.path.abspath(os.curdir))
        print('User: {}'.format(gxp.gid))

        # get command line parameters
        parser = argp.ArgumentParser(description="Add a constant to a Geosoft database channel")
        parser.add_argument("sDB", help="Geosoft database")
        parser.add_argument("sCh", help="channel to process")
        parser.add_argument("-v",
                            "--value",
                            type=float,
                            default=1.0,
                            help="value to add, default is 1.0")
        args = parser.parse_args()

        # echo parameters
        print("\nDatabase = "+args.sDB)
        print("Channel = "+args.sCh)
        print("Value to add = {}\n".format(args.value))

        # open the database
        with gxpy.gdb.Geosoft_gdb.open(args.sDB) as db:

            # process the data
            process_database(db, args.sCh, args.value)