Subsections

 
10 Function and Object Reference

Note: This section is incomplete. More information will be added later.

The base classes for PyRAF tasks and parameters are IrafTask and IrafPar respectively; IrafParList is the class for a list of PyRAF parameters. These are used in the Python equivalent of CL scripts, and they include methods that are generally useful as well. getCode(), for example, is a method of IrafCLTask (which inherits IrafTask). This section describes some of the more useful methods of these classes, as well as some utility functions. A more complete description of these and some other classes will be added to this document at a later time.

10.1 Example

As an example, it may be helpful to explain the syntax of the Python equivalent of this very simple CL script:

procedure ttt(input)

string input = "" {prompt = "name of input image"}
string mode = "al"

begin
        imstat(input)
end

This is the Python equivalent, obtained by iraf.ttt.getCode():

from pyraf import iraf
from pyraf.irafpar import makeIrafPar, IrafParList
from pyraf.irafglobals import *
import math

def ttt(input='', mode='al', DOLLARnargs=0, taskObj=None):

    Vars = IrafParList('ttt')
    Vars.addParam(makeIrafPar(input, datatype='string', name='input', mode='a',
        prompt='input image'))
    Vars.addParam(makeIrafPar(mode, datatype='string', name='mode', mode='h'))
    Vars.addParam(makeIrafPar(DOLLARnargs, datatype='int', name='$nargs',
        mode='h'))

    iraf.imstat(Vars.input)

The makeIrafPar() function and IrafParList class are imported from pyraf.irafpar because the script will use these for defining the task parameters. The irafglobals module defines a variety of things that may be used in CL scripts, such as the IRAF boolean values yes and no, EOF (end of file), and INDEF, which is often used as the initial value for task parameters.

IrafParList returns an object (Vars) that will contain a list of all the parameters for the task, in the form of IrafPar objects. makeIrafPar() returns an IrafPar object. An alternative to makeIrafPar() is the IrafParFactory() function, but its arguments correspond to the comma-separated descriptors in IRAF par files, and this is not very intuitive unless one is rather familiar with these files. The addParam() method of IrafParList appends the IrafPar object to the parameter list.

The imstatistics task is called with the value of the ttt.input parameter as the image name. Note that attribute syntax is used to get the value of this parameter. An alternative would be to use the getValue() method of IrafParList, but unless native=1 is specified, getValue returns the value as a string, which could conflict with the data type expected by the called task. Using attribute syntax with the parameter name, the parameter value is returned with the ``native'' data type.

10.2 IrafTask

IrafTask is the base class for several more specific classes, such as IrafCLTask, IrafPkg, IrafPset, IrafPythonTask and IrafForeignTask. These would not normally be instantiated directly by a user or programmer. Once a task has been defined in PyRAF, the IRAF task object is ``iraf.'' followed by the task name. The task name can be abbreviated as long as the portion that was specified is unique (``minimum match''). The code for IrafTask is in iraftask.py in the pyraf directory. The following describes some of the methods in IrafTask.

Parameter values may be set or gotten using the setParam() or getParam() method respectively. In the argument list, qualifiedName is the parameter name; the ``qualified'' part means that it may be prefixed by the task or package name, or it may have an index (for an array parameter) or a field specification. The field is what is referred to as a ``parameter attribute'' in the IRAF help page for parameters (type phelp parameters). The fields that may be set are p_value, p_prompt, p_filename, p_minimum, p_maximum, p_mode. The fields that may be gotten are p_name, p_value, p_default, p_xtype, p_type, p_prompt, p_filename, p_minimum, p_maximum, p_mode. Specify exact=1 to disable minimum matching for the parameter name and qualifiers. The default check=1 in setParam() means that the new value will be checked to see that it is within the minimum and maximum, or within the choice list for a string. The default native=0 in getParam() means that the returned value will be a string; specify native=1 to ensure that the returned value be in the ``native'' data type for the parameter.

getParObject(paramname, exact=0, alldict=0) returns the IrafPar object for paramname. The default exact=0 means that minimum matching is allowed for the parameter name. The default alldict=0 means that the parameter will be searched for only within the parameter list(s) for the current task, i.e. the parameter list for the task itself and all its psets. Specify alldict=1 to enable searching for the parameter in all loaded tasks and packages, including the CL. One reason why it may be useful to get the IrafPar object is to make use of the methods in that class (see below).

The lParam(verbose=0) and dParam(cl=1) methods are like the lparam and dparam commands, or the iraf.lparam() and iraf.dparam() functions in the iraf module. Specifying verbose=1 when calling lParam means that the minimum and maximum values or the choice list will also be printed, if these are defined. By default, dParam prints parameters and values the way IRAF's dparam does. The default cl=1 means that the output will be in IRAF syntax, while specifying cl=0 results in Python syntax. One difference is that with cl=0 each line will begin with ``iraf.'', e.g. iraf.imstatistics.images = 'l61h.fits[1]'. Another is that if a parameter value was not specified, cl=0 results in par = None, while cl=1 results in par = . Note that ``not specified'' in this case is not the same as INDEF or ""; it means that the parameter file does not give a default value and none has been assigned.

unlearn() deletes the copy of the parameter file from the user's uparm directory and resets the ``current'' parameter list to the default values which are defined in the original (template) parameter file.

10.3 IrafPar

IrafPar is the base class for scalar parameters. There is one subclass for each data type (or set of closely related types) that a parameter may have. Other base classes are IrafArrayPar and IrafParL, for array parameters and list-directed parameters respectively. Multiple inheritance with a ``mix-in'' design is used to construct classes for different parameter types, such as strings and list-directed parameters. The code for IrafPar is in irafpar.py in the pyraf directory. The following describes some of the methods in the IrafPar class.

getWithPrompt() prints the prompt string and current value, gives the user the option to supply a new value (using tkreadline), and it updates the value attribute in the IrafPar object with the new value. It does not return the value.

get(field=None, index=None, lpar=0, prompt=1, native=0, mode="h") returns the value (or other field) of the parameter, prompting the user if mode="q" (or if mode inherits ``q'' from the CL). The parameter value (p_value) is the default for field; the options for field are (these are all strings, and minimum matching may be used when specifying them): p_name, p_type, p_xtype, p_value, p_prompt, p_minimum, p_maximum, p_filename, p_mode, p_default. Note that p_length is defined for IRAF string parameters, but this is not needed in PyRAF and has not been defined.

set(value, field=None, index=None, check=1) sets the value (or other field) of the parameter. Specifying check=0 allows the parameter value to be outside the range from minimum to maximum (or not in the choice list for a string or integer parameter).

checkValue(value, strict=0) checks whether the specified value is within the range of allowed values, i.e. between the minimum and maximum for numeric parameters, or in the choice list if the object is a string or integer parameter. The specified value does not need to be of the same type as the parameter; the value will be converted to the correct type before being compared with the range of legal values. If the value is legal, the value converted to the correct type (or None) will be returned; if not, a ValueError exception will be raised.

dpar(cl=1) returns a string with ``name = value'' for the parameter. If the parameter is a string, the value will be enclosed in quotes. cl=1 means write the assignments in a format that would be accepted by the iraf cl; cl=0 means that if the parameter is a string and its value is null, the value will be shown as None instead of ``''.

pretty(verbose=0) returns a string with the parameter description as it would appear if the user typed the IRAF lparam command. String values will not be enclosed in quotes. If verbose=1 is specified, the string includes the choice list or allowed range. For example:

--> print iraf.imarith.getParObject("op").pretty(verbose=1)
           op = +               Operator
                                |+|-|*|/|min|max|
--> print iraf.sgraph.getParObject("left").pretty(verbose=1)
        (left = 0.0)            Left edge of viewport [NDC]
                                0.0 <= left <= 1.0

save(dolist=0) returns a string with the parameter information formatted as you would see it in a parameter file. If dolist=1, the returned value will instead be a list of strings, one for each of the various components.

The makeIrafPar() factory function is a convenient way to create an IrafPar object from scratch:

makeIrafPar(init_value, datatype=None, name="<anonymous>", mode="h", array_size=None, list_flag=0, min=None, max=None, enum=None, prompt="", strict=0)

init_value can be an initial value, but an alternative is for it to already be an IrafPar object, in which case that object will simply be returned unchanged. datatype must be specified; the options are (these are strings): string, char, file, struct, int, bool, real, double, gcur, imcur, ukey, pset. Leave array_size=None (not 0) for a scalar parameter. Leave min=None when specifying enum (a choice list of possible values for a string parameter). A choice list can be given for an integer parameter as well, e.g. enum = "36|37|38"; this is an option which is not supported in IRAF. There is also a filename argument, but its use is deprecated. The default strict=0 means that the function attempts to work around errors when reasonable; use strict=1 to raise an exception for any error.

--> print pyraf.irafpar.makeIrafPar(3.141592653589793, datatype="real",
... name="pi", prompt="test")
<IrafParR pi r h 3.1415926535900001 None None "test">

There are a number of utility functions in PyRAF that are defined in the file iraffunctions.py in the pyraf directory. There are of order 100 of these functions. Some implement functions in the IRAF CL, while others are unique to PyRAF.

Here are descriptions of the more useful of these functions in iraffunctions.py.

Note: More detailed descriptions for these functions will be added later. The descriptions shown are taken from the doc strings.

help(object=__main__, variables=1, functions=1, modules=1, tasks=0, packages=0, hidden=0, padchars=16, regexp=None, html=0, **kw)
(This function is actually defined in irafhelp.py.)
List the type and value of all the variables in the specified object.

- help() with no arguments will list all the defined variables.
- help("taskname") or help(IrafTaskObject) displays IRAF help for the task
- help(object) where object is a module, instance, etc., will display information on the attributes and methods of the object.
- help(function) will give the calling sequence for the function.

Optional keyword arguments specify what information is to be printed. The keywords can be abbreviated:

variables=1 Print info on variables/attributes
functions=1 Print info on function/method calls
modules=1 Print info on modules
tasks=0 Print info on IrafTask objects
packages=0 Print info on IrafPkg objects
hidden=0 Print info on hidden variables/attributes (starting with '_')
html=0 Use HTML help instead of standard IRAF help for tasks

regexp=None Specify a regular expression that matches the names of variables of interest. For example, help(sys, regexp='std') will give help on all attributes of sys that start with std. All the re patterns can be used.

Other keywords are passed on to the IRAF help task if it is called.

defpar(paramname)
Returns true if parameter is defined.

access(filename)
Returns true if file exists.

imaccess(filename)
Returns true if image matching name exists and is readable.

defvar(varname)
Returns true if CL variable is defined.

deftask(taskname)
Returns true if CL task is defined.

defpac(pkgname)
Returns true if CL package is defined and loaded.

boolean(value)
Convert Python native types (string, int, float) to IRAF boolean.

fscan(locals, line, *namelist, **kw)
fscan function sets parameters from a string or list parameter.

Uses local dictionary (passed as first argument) to set variables specified by list of following names. (This is a bit messy, literally using call-by-name for these variables.)

Accepts an additional keyword argument strconv with names of conversion functions for each argument in namelist.

Returns number of arguments set to new values. If there are too few space-delimited arguments on the input line, it does not set all the arguments. Returns EOF on end-of-file.

fscanf(locals, line, format, *namelist, **kw)
fscanf function sets parameters from a string/list parameter with format.

Implementation is similar to fscan but is a bit simpler because special struct handling is not needed. Does not allow strconv keyword.

Returns number of arguments set to new values. If there are too few space-delimited arguments on the input line, it does not set all the arguments. Returns EOF on end-of-file

scan(locals, *namelist, **kw)
Scan function sets parameters from line read from stdin.

This can be used either as a function or as a task (it accepts redirection and the _save keyword.)

scanf(locals, format, *namelist, **kw)
Formatted scan function sets parameters from line read from stdin.

This can be used either as a function or as a task (it accepts redirection and the _save keyword.)

nscan()
Return number of items read in last scan function.

set(*args, **kw)
Set IRAF environment variables.

show(*args, **kw)
Print value of IRAF or OS environment variables.

unset(*args, **kw)
Unset IRAF environment variables.

This is not a standard IRAF task, but it is obviously useful. It makes the resulting variables undefined. It silently ignores variables that are not defined. It does not change the OS environment variables.

time(**kw)
Print current time and date.

beep(**kw)
Beep to terminal (even if output is redirected).

clOscmd(s, **kw)
Execute a system-dependent command in the shell, returning status.

stty(terminal=None, **kw)
IRAF stty command (mainly not implemented).

edit(*args, **kw)
Edit text files.

clear(*args, **kw)
Clear screen if output is terminal.

flprcache(*args, **kw)
Flush process cache. Takes optional list of tasknames.

prcache(*args, **kw)
Print process cache. If args are given, locks tasks into cache.

gflush(*args, **kw)
Flush any buffered graphics output.

history(n=20, *args, **kw)
Print history.

Does not replicate the IRAF behavior of changing default number of lines to print.

hidetask(*args, **kw)
Hide the CL task in package listings.

task(*args, **kw)
Define IRAF tasks.

redefine(*args, **kw)
Redefine an existing task.

package(pkgname=None, bin=None, PkgName="", PkgBinary="", **kw)
Define IRAF package, returning tuple with new package name and binary.

PkgName, PkgBinary are old default values. If Stdout=1 is specified, returns output as string array (normal task behavior) instead of returning PkgName, PkgBinary. This inconsistency is necessary to replicate the inconsistent behavior of the package command in IRAF.

clPrint(*args, **kw)
CL print command - emulates CL spacing and uses redirection keywords.

printf(format, *args, **kw)
Formatted print function.

pwd(**kw)
Print working directory.

chdir(directory=None, **kw)
Change working directory.

cd(directory=None, **kw)
Change working directory (same as chdir).

back(**kw)
Go back to previous working directory.

Expand(instring, noerror=0)
Expand a string with embedded IRAF variables (IRAF virtual filename).

Allows comma-separated lists. Also uses os.path.expanduser to replace '~' symbols. Set noerror flag to silently replace undefined variables with just the variable name or null (so Expand("abc$def") = "abcdef" and Expand("(abc)def") = "def"). This is the IRAF behavior, though it is confusing and hides errors.

load(pkgname, args=(), kw=None, doprint=1, hush=0, save=1)
Load an IRAF package by name.

run(taskname, args=(), kw=None, save=1)
Run an IRAF task by name.

getAllTasks(taskname)
Returns list of names of all IRAF tasks that may match taskname.

getAllPkgs(pkgname)
Returns list of names of all IRAF packages that may match pkgname.

getTask(taskname, found=0)
Find an IRAF task by name using minimum match.

Returns an IrafTask object. Name may be either fully qualified (package.taskname) or just the taskname. taskname is also allowed to be an IrafTask object, in which case it is simply returned. Does minimum match to allow abbreviated names. If found is set, returns None when task is not found; default is to raise exception if task is not found.

getPkg(pkgname, found=0)
Find an IRAF package by name using minimum match.

Returns an IrafPkg object. pkgname is also allowed to be an IrafPkg object, in which case it is simply returned. If found is set, returns None when package is not found; default is to raise exception if package is not found.

getTaskList()
Returns list of names of all defined IRAF tasks.

getTaskObjects()
Returns list of all defined IrafTask objects.

getPkgList()
Returns list of names of all defined IRAF packages.

getLoadedList()
Returns list of names of all loaded IRAF packages.

getVarDict()
Returns dictionary of all IRAF variables.

getVarList()
Returns list of names of all IRAF variables.

listAll(hidden=0, **kw)
List IRAF packages, tasks, and variables.

listPkgs(**kw)
List IRAF packages.

listLoaded(**kw)
List loaded IRAF packages.

listTasks(pkglist=None, hidden=0, **kw)
List IRAF tasks, optionally specifying a list of packages to include.

Package(s) may be specified by name or by IrafPkg objects.

listCurrent(n=1, hidden=0, **kw)
List IRAF tasks in current package (equivalent to `?' in the cl).

If parameter n is specified, lists n most recent packages.

listVars(prefix="", equals="\t= ", **kw)
List IRAF variables.

curpack()
Returns name of current CL package.

curPkgbinary()
Returns name of pkgbinary directory for current CL package.

pkgHelp(pkgname=None, **kw)
Give help on package (equivalent to CL `? [taskname]').

allPkgHelp(**kw)
Give help on all packages (equivalent to CL `??').

clCompatibilityMode(verbose=0, _save=0)
Start up full CL-compatibility mode.

clArray(array_size, datatype, name="<anonymous>", mode="h", min=None, max=None, enum=None, prompt=None, init_value=None, strict=0)
Create an IrafPar object that can be used as a CL array.

clExecute(s, locals=None, mode="proc", local_vars_dict=, local_vars_list=[], verbose=0, **kw)
Execute a single cl statement.

IrafTaskFactory(prefix="", taskname=None, suffix="", value=None, pkgname=None, pkgbinary=None, redefine=0, function=None)
Returns a new or existing IrafTask, IrafPset, or IrafPkg object.

Type of returned object depends on value of suffix and value.

Returns a new object unless this task or package is already defined. In that case if the old task appears consistent with the new task, a reference to the old task is returned. Otherwise a warning is printed and a reference to a new task is returned.

If redefine keyword is set, the behavior is the same except a warning is printed if it does not exist.

Questions or comments? Contact help@stsci.edu
Documented updated on