Python User's Guide for STAF V2

Last Updated: May 11, 2005

1.0 Introduction

This document describes STAF's V2.x 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, select to install the "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.

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 V2 Python support is provided via the STAF Support Requests:

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.

3.0 PySTAF module

The PySTAF module provides the base level of support for Python scripts to call into STAF.  This package externalizes three classes and a utility function To use this module you simply import it like so

from PySTAF import *

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 STAFHandle class

Description

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.

(Pseudo) Definition

class STAFHandle:

    # Handle types

    Standard = 0
    Static   = 1

    # Submission modes

    Synchronous   = 0
    FireAndForget = 1
    Queue         = 2
    Retain        = 3
    QueueRetain   = 4

    def __init__(nameOrHandle, standardOrStatic = STAFHandle.Static)
    def submit(location, service, request, mode=STAFHandle.Synchronous)
    def unregister()

The __init__() method generates an instance of STAFException if the STAFHandle object could not be created.  The submit() method returns an instance of class STAFResult, described below.

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 {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.  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.

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 STAFResult class

Description

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.

(Pseudo) Definition

class STAFResult:

    # Exposes two variables:
    #
    # rc     - The numeric return code of the service request
    # result - The string result buffer returned from the service request

    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
    ServiceAlreadyExists        = 40
    InvalidObject               = 41
    InvalidParm                 = 42
    RequestNumberNotFound       = 43
    InvalidAsynchOption         = 44
    RequestNotComplete          = 45
    ProcessAuthenticationDenied = 46
    InvalidValue                = 47
    DoesNotExist                = 48
    AlreadyExists               = 49
    DirectoryNotEmpty           = 50
    DirectoryCopyError         = 51

    def __init__(rc = 0, result = "")

Examples

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

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

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

print "Ping request RC: %d" % result.rc
print "Ping request result buffer: %s" % result.result

3.3 STAFException class

Description

This class is the base exception class used by the STAF modules.  Currently, this class is only used when trying to register with STAF.

(Pseudo) Definition

class STAFException:

    # Exposes two variables:
    #
    # rc     - The numeric return code which is the basis of the exception
    # result - A string futher describing the exception

    def __init__(rc = 0, result = ""):

Examples

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

from PySTAF import *
import sys

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

3.4 STAFWrapData function

Description

This function takes a string and produces the colon-length-colon delimited version of that string.  This function is widely used to pass the values of options in STAF requests.

Syntax

outputString = STAFWrapData(inputString)

Example

semName = "My Synch Sem"

result = handle.submit("local", "sem", "event %s post" % STAFWrapData(semName))

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 STAFMonitor class

Description

This class provides 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.

(Pseudo) Definition

class STAFMonitor:

    InvalidDirectory     = 4005
    CreateDirectoryError = 4006
    InvalidLogFileFormat = 4007

    def __init__(stafHandle, system = "local", service = "Monitor"):
    def log(message):

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.

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 STAFLog class

Description

This class provides 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.

(Pseudo) Definition

class STAFLog:

    # 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

    InvalidNumber               = 4001
    InvalidDate                 = 4002
    InvalidTime                 = 4003
    InvalidLevel                = 4004
    InvalidDirectory            = 4005
    InvalidCreateDirectoryError = 4006
    InvalidLogFileFormat        = 4007
    PurgeFailure                = 4008
    UnknownRemoteLogServer      = 4009

    def __init__(handle, type, name, monitorMask = [ "Fatal", "Error",
                 "Warning", "Start", "Stop", "Pass", "Fail" ],
                 system = "local", service = "Log"):
    def log(level, msg):

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

Examples

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

from PySTAFLog import *

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

# Let's create a machine based log file that also sends fatal, error, and
# warning messages to the Monitor service

log = STAFLog(handle, STAFLog.Machine, "MyLog",
              [STAFLog.Fatal, STAFLog.Error, STAFLog.Warning])

# This message will only go to the log service, since we didn't specify
# that start message get sent to the Monitor service

result = log.log(STAFLog.Start, "Beginning ABC test")

# This message will be sent to the Log and Monitor services

result = log.log(STAFLog.Warning, "Got some ambiguous result")