Python User's Guide for STAF Version 3

Last Updated: March 3, 2006


Table of Contents

1.0 Introduction

2.0 Installation

3.0 Module PySTAF

3.1 Class STAFHandle
3.2 Class STAFResult
3.3 Class STAFException
3.4 Class STAFMapClassDefinition
3.5 Class STAFMarshallingContext
3.6 Function isMarshalledData
3.7 Function marshall
3.8 Function unmarshall
3.9 Function formatObject
3.10 Function wrapData
3.11 Function addPrivacyDelimiters
3.12 Function escapePrivacyDelimiters
3.13 Function removePrivacyDelimiters
3.14 Function maskPrivateData
3.15 Constants
4.0 Module PySTAFMon 4.1 Class STAFMonitor 5.0 Module PySTAFLog 5.1 Class STAFLog


1.0 Introduction

This document describes STAF's V3 support for the Python language.  It includes information on the core STAF Python APIs as well as the wrappers provided for the Monitor and Log services.

2.0 Installation

To install STAF's Python support on Windows or Linux 32-bit platforms, select to install "Python support" during the install. It is installed by default for a "typical" install of STAF.

The version of Python used to build the STAF Python libraries is the only Python version that will work with those STAF Python libraries.

Once STAF's Python support is installed, you need to set/update your PYTHONPATH environment variable. On Unix, add the /usr/local/staf/lib directory to your PYTHONPATH, assuming you installed STAF to directory /usr/local/staf. On Win32, add the C:\STAF\bin directory to your PYTHONPATH, assuming you installed STAF to directory C:\STAF.

Finally, you simply need to import the modules described below.

Note: You can build STAF Python support yourself if you want to use a different version of Python or if you want STAF Python support for a different operating system. See the STAF Developer's Guide for more information on how to build the STAF python project. Or, you can submit a Support Request via the STAF SourceForge website for us to build it for you (but it may take a while until we get a chance to implement your request). Be sure to check the existing STAF Support Requests as we may have already provided STAF Python support for the Python version and operating system that you want and attached it to an existing STAF Support Request. For example, the following additional STAF V3 Python support is provided via the STAF Support Requests:

If you build STAF Python support for a different operating system and/or different Python version, please contribute it to the STAF project. To contribute it, browse the STAF Support Requests to see if someone else has already provided STAF Python support for this operating system and Python version combination. If not, open a STAF Support Request with the "Summary" containing "STAF V3 Support for Python x.x.x (Platform)", replacing x.x.x with the Python version and replacing Platform with the operating system on which you built the support. Attach the necessary file (e.g. PYSTAF.dll on Windows or PYSTAF.so for Unix) to the Support Request.


3.0 Module PySTAF

The PySTAF module provides the base level of support for Python scripts to call into STAF. This package externalizes some classes, utility functions, and constants.

The STAF Python classes that it externalizes are:

The STAF Python functions that it externalizes are:

To use this module you simply import it like so:

Since the STAF Python libraries include several files with "PYSTAF" as their file name (with varying cases, i.e. PySTAF, PYSTAF), make sure that you are not using the "PYTHONCASEOK" environment variable. For example, if you have it set as "PYTHONCASEOK=1" and then try to use the STAF Python libraries, you will get the following error:

Traceback (most recent call last):
  File "TestPython.py", line 9, in ?
    from PySTAF import *
ImportError: dynamic module does not define init function (initPySTAF)

To correct this error, set "PYTHONCASEOK=".

3.1 Class STAFHandle

Definition

class STAFHandle(handleNameOrNumber[, handleType])
This class is the primary class used to communicate with STAF. The primary method of interest is the submit() method, which allows your Python script to call STAF services. If a STAFHandle object could not be created, an instance of STAFException is generated.

The required argument handleNameOrHandle specifies a handle name or number.

The optional argument handleType specifies the type of handle. Valid handle types are STAFHandle.Standard and STAFHandle.Static. The default is STAFHandle.Standard.

STAFHandle defines the following methods:

STAFHandle defines the following constants:

    # STAFHandle types

    Standard = 0
    Static   = 1

    # Modes for submit call

    Synchronous   = 0
    FireAndForget = 1
    Queue         = 2
    Retain        = 3
    QueueRetain   = 4
Note, you can obtain more information on standard vs. static handles and the various submission modes in the C API reference in the STAF User's Guide.

Examples

The following is an example of a program which registers with STAF, calls a couple of STAF services, and then unregisters with STAF.
    from PySTAF import *
    import sys

    try:
        handle = STAFHandle("MyTest")
    except STAFException, e:
        print "Error registering with STAF, RC: %d" % e.rc
        sys.exit(e.rc)

    result = handle.submit("local", "ping", "ping")

    if (result.rc != 0):
        print "Error submitting request, RC: %d, Result: %s" % (result.rc, result.result)

    result = handle.submit("local", "var", "resolve string {STAF/Config/OS/Name}")

    if (result.rc != 0):
        print "Error submitting request, RC: %d, Result: %s" % (result.rc, result.result)
    else:
        print "OS Name: %s" % result.result

    rc = handle.unregister()

    sys.exit(rc)

The following is an example which uses a static STAF handle to call STAF asynchronously and then waits for the result of the call to come back.
    from PySTAF import *

    # Other code would be in here that obtains a static handle number from somewhere.
    # See section 5.2 of the STAF User's Guide for more information on static handles.
 
    try:
        handle = STAFHandle(staticHandleNumber, STAFHandle.Static)
    except STAFException, e:
        print "Error registering with STAF, RC: %d" % e.rc
        sys.exit(e.rc)

    result = handle.submit("local", "fs", "copy file /tmp/abc tomachine xyz", STAFHandle.Queue)

    if (result.rc != 0):
        print "Error submitting request, RC: %d, Result: %s" % (result.rc, result.result)

    requestNumber = result.result

    # At this point I can do some other work while the file transfer completes
 
    ...
    
    # And now, I want to wait until the request has completed
    
    result = handle.submit("local", "queue", "get contains %s wait") % \
             STAFWrapData("STAF/RequestComplete %s;" % requestNumber))

    # result.result now contains a message which includes the result of FS service request.
    # I can now check the result and/or continue with the rest of my script

3.2 Class STAFResult

Definition

class STAFResult([rc][, result])
This class encapsulates the result of a STAF service request (made via the STAFHandle.submit() method). This class also contains a set of constants representing the various common STAF return codes.

The optional argument rc specifies the numeric return code of the service request. The default is 0.
The optional argument result specifies a string result buffer returned from the service request. The default is "".

STAFResult defines the following member variables. They are initialized by the constructor, and should not be modified directly.

STAFResult defines the following constants representing the various common STAF return codes.

    Ok                          = 0
    InvalidAPI                  = 1
    UnknownService              = 2
    InvalidHandle               = 3
    HandleAlreadyExists         = 4
    HandleDoesNotExist          = 5
    UnknownError                = 6
    InvalidRequestString        = 7
    InvalidServiceResult        = 8
    REXXError                   = 9
    BaseOSError                 = 10
    ProcessAlreadyComplete      = 11
    ProcessNotComplete          = 12
    VariableDoesNotExist        = 13
    UnResolvableString          = 14
    InvalidResolveString        = 15
    NoPathToMachine             = 16
    FileOpenError               = 17
    FileReadError               = 18
    FileWriteError              = 19
    FileDeleteError             = 20
    STAFNotRunning              = 21
    CommunicationError          = 22
    TrusteeDoesNotExist         = 23
    InvalidTrustLevel           = 24
    AccessDenied                = 25
    STAFRegistrationError       = 26
    ServiceConfigurationError   = 27
    QueueFull                   = 28
    NoQueueElement              = 29
    NotifieeDoesNotExist        = 30
    InvalidAPILevel             = 31
    ServiceNotUnregisterable    = 32
    ServiceNotAvailable         = 33
    SemaphoreDoesNotExist       = 34
    NotSemaphoreOwner           = 35
    SemaphoreHasPendingRequests = 36
    Timeout                     = 37
    JavaError                   = 38
    ConverterError              = 39
    InvalidObject               = 41
    InvalidParm                 = 42
    RequestNumberNotFound       = 43
    InvalidAsynchOption         = 44
    RequestNotComplete          = 45
    ProcessAuthenticationDenied = 46
    InvalidValue                = 47
    DoesNotExist                = 48
    AlreadyExists               = 49
    DirectoryNotEmpty           = 50
    DirectoryCopyError          = 51
    DiagnosticsNotEnabled       = 52
    HandleAuthenticationDenied  = 53
    HandleAlreadyAuthenticated  = 54
    InvalidSTAFVersion          = 55
    RequestCancelled            = 56

Examples

The following example shows the use of the STAFResult class in calling a STAF service.

3.3 Class STAFException

Definition

class STAFException([rc][, result])
This class is the base exception class used by the STAF modules. Currently, this class is only used when trying to register or unregister with STAF.

The optional argument rc specifies the numeric return code which is the basis of the exception. The default is 0.
The optional argument result specifies a string which further describes the exception. The default is "".

STAFException defines the following member variables. They are initialized by the constructor, and should not be modified directly.

Examples

The following is an example of a program which shows how to deal with a STAFException when registering with STAF.

3.4 Class STAFMapClassDefinition

Definition

class STAFMapClassDefinition([name])
A class which provides the metadata associated with a map class. In particular, it defines the keys associated with the map class. This class is used to create and/or access a STAF map class definition which can be useful if you want to generate a STAF marshalling context with map classes. The map class definition is used to reduce the size of a marshalling map class in comparison to a map containing the same data. It also contains information about how to display instances of the map class, such as the order in which to display the keys and the display names to use for the keys. You get and set map class definitions using the STAFMarshallingContext class setMapClassDefinition and getMapClassDefinition functions.

The optional keyword argument name specifies the name of the STAF map class definition. The default is None.

STAFMapClassDefinition defines the following methods:

Example

The following is an example of how to create a map class definition named 'Test/MyMap' containing four keys, each with a display name, and one with a short display name. This example prints the following:

3.5 Class STAFMarshallingContext

Definition

class STAFMarshallingContext([obj])
A class is used to create and/or access a STAF marshalling context which is used by STAF to help in marshalling and unmarshalling data. A marshalling context is simply a container for map class definitions and a data structure that uses (or is defined in terms of) them.

In order to use a map class when marshalling data, you must add the map class definition to the marshalling context, set the root object of the marshalling context to the object you want to marshall, and then marshall the marshalling context itself. When you unmarshall a data structure, you will always receive a marshalling context. Any map class definitions referenced by map classes within the data structure will be present in the marshalling context.

The primary use of this class is to represent multi-valued results that consist of a data structure (e.g. results from a QUERY/LIST service request, etc.) as a string that can also be converted back into the data structure. This string can be assigned to the string result buffer returned from the service request.

The optional keyword argument obj specifies the root object to be marshalled. The default is None.

STAFMarshallingContext defines the following methods:

Examples

The following is an example of how to create a marshalling context containing one map class definition named 'Test/MyMap' and a root object which is a list of maps defined by the map class definition. Then it shows how to marshall and unmarshall the marshalling context. This example prints the following:

3.6 Function isMarshalledData

Definition

Example

3.7 Function marshall

Definition

Examples

This example converts a Python dictionary and converts it into a string-based marshalled representation. It also shows how to convert this marshalled string back into the original Python dictionary.

This example creates a marshalling context with one map class definition and a Python list where each entry is a map. It then creates a string-based marshalled representation of it.

3.8 Function unmarshall

Definition

Example

3.9 Function formatObject

Definition

Examples

This example that prints a Python dictionary in a "pretty" verbose format: This could result in the following output printed:

This example prints the result from a FS QUERY ENTRY request in a "pretty" verbose format:

If successful, this could result in the following output printed: However, note that specifying instead of specifying formatObject(mc.getRootObject(), mc), you could just print the marshalling context itself, mc, to get the same output as the str function for a STAFMarshallingContext object calls the formatObject function. For example:

3.10 Function wrapData

Definition

Note that STAFWrapData is an alias for the wrapData function and can be used instead to call this function.

Examples

This example creates a colon-length-colon delimited version of string Hello world. The resulting string is :11:Hello world. This example uses the wrapData function for the semaphore name (which contains spaces) in an EVENT POST request to the SEM service.

3.11 Function addPrivacyDelimiters

Definition

Note that STAFAddPrivacyDelimiters is an alias for the addPrivacyDelimiters function and can be used instead to call this function.

Examples

This example adds privacy delimiters to 'passw0rd' used in the PASSWORD option when starting a process as another user. This example adds privacy delimiters to password 'secret' used in the COMMAND option when starting a process.

3.12 Function escapePrivacyDelimiters

Definition

Note that STAFEscapePrivacyDelimiters is an alias for the escapePrivacyDelimiters function and can be used instead to call this function.

Examples

This example escapes privacy delimiters in password 'passw@!!d' before adding privacy delimiters to it and then uses the password in the PASSWORD option when starting a process as another user.

3.13 Function removePrivacyDelimiters

Definition

Note that STAFRemovePrivacyDelimiters is an alias for the removePrivacyDelimiters function and can be used instead to call this function.

Examples

This example removes privacy delimiters from protected password '!!@secret@!!' and assigns 'secret' as the password.

3.14 Function maskPrivateData

Definition

Note that STAFMaskPrivateData is an alias for the maskPrivateData function and can be used instead to call this function.

Examples

This example masks any private data indicated by privacy delimiters in a request string before displaying it. This example prints:
START COMMAND C:/tests/TestA.exe USERNAME Test1 PASSWORD **************

3.15 Constants

Constants defined in this module include:


4.0 Module PySTAFMon

The PySTAFMon module provides a class to ease the use of the Monitor service.  To use this module you simply import it like so:
    from PySTAFMon import *

4.1 Class STAFMonitor

Definition

class STAFMonitor(stafHandle[, system][, service])
A class used to provide a wrapper around the Monitor service. It also contains a set of constants representing the Monitor service return codes. The primary method of interest is the log() method which allows you to log a message to the STAF Monitor service.

The required keyword argument stafHandle specifies the STAF handle to use to submit the request to the Monitor service.

The optional keyword argument system specifies the endpoint of the machine to submit the request to. The default is "local".

The optional keyword argument service specifies the registered name of the STAF Monitor service. The default is "Monitor".

Note: By default, the STAFMonitor class will use the service named "Monitor" on the local system. This can be changed by explicitly specifying the system and/or service when you construct the STAFMonitor object.

STAFMonitor defines the following methods:

Examples

The following example shows the use of the STAFMonitor class to log a status message to the Monitor service.
    from PySTAFMon import *

    # The variable "handle" is an instance of the STAFHandle class that was
    # previously instantiated

    monitor = STAFMonitor(handle)
    result = monitor.log("Beginning section ABC of test")


5.0 Module PySTAFLog

The PySTAFLog module provides a class to ease the use of the Log service.  To use this module you simply import it like so:
    from PySTAFLog import *

5.1 Class STAFLog

Definition

class STAFLog(handle, logType, name[, monitorMask][, system][, service])
A class used to provide a wrapper around the Log service. It provides a log() method for logging a message to the Log service. It also contains constants for the various log file types and logging levels, as well as the return codes returned by the Log service. This wrapper also allows you to specify a set of log levels for which the messages logged to the Log service will also be logged to the Monitor service.

The required keyword argument handle specifies the STAF handle to use to submit the request to the Log service.

The required keyword argument logType specifies the log type (e.g. STAFLog.Global, STAFLog.Machine, or STAFLog.Handle)

The required keyword argument name specifies the name of the log.

The optional keyword argument monitorMask specifies a mask that consists of a list of logging levels. This list controls which messages are also sent to the Monitor service. The default is to enable "Fatal", "Error", "Warning", "Start", "Stop", "Pass", and "Fail". If there is an error logging, STAFLog will also try to send an error to the Monitor service.

The optional keyword argument system specifies the endpoint of the machine to submit the log request to. The default is "local".

The optional keyword argument service specifies the registered name of the STAF Log service. The default is "Log".

Note: By default, the STAFLog class will use the service named "Log" on the local system. This can be changed by explicitly specifying the system and/or service when you construct the STAFLog object.

STAFLog defines the following methods:

STAFLog defines the following constants:

    # Log type constants

    Global  = "GLOBAL"
    Machine = "MACHINE"
    Handle  = "HANDLE"

    # Log level constants

    Fatal     = "Fatal"
    Error     = "Error"
    Warning   = "Warning"
    Info      = "Info"
    Trace     = "Trace"
    Trace2    = "Trace2"
    Trace3    = "Trace3"
    Debug     = "Debug"
    Debug2    = "Debug2"
    Debug3    = "Debug3"
    Start     = "Start"
    Stop      = "Stop"
    Pass      = "Pass"
    Fail      = "Fail"
    Status    = "Status"
    User1     = "User1"
    User2     = "User2"
    User3     = "User3"
    User4     = "User4"
    User5     = "User5"
    User6     = "User6"
    User7     = "User7"
    User8     = "User8"

    # Log service return codes

    InvalidLevel                = 4004
    InvalidLogFileFormat        = 4007
    PurgeFailure                = 4008

Examples

The following example shows the use of the STAFLog class to log some messages.

*** End of Document ***