The Python to IDL bridge provides a mechanism for calling IDL code from Python. The IDL module contains a set of methods that allow you to initialize and interact with the IDL interpreter. In addition, each object passed back from IDL is wrapped in an instance of the IDL class; you can then call methods on the underlying IDL object, or set and retrieve attributes on the object.
Note: See Python Bridge for installation instructions.
Methods and Additional Information
See also Python Bridge: Parameter Passing and Data Conversion.
Examples
Call an IDL function or method directly from Python code, as if it was a Python object:
>>> from idlpy import *
>>> arr = IDL.findgen(100)/50*3.14159
>>> x = 50*IDL.sin(arr)
>>> y = 50*IDL.cos(arr)
>>> m = IDL.map(test=1)
% Compiled module: MAP.
>>> p = IDL.plot(x - 90, y, 'r-o2', overplot=1)
% Compiled module: PLOT.
>>> p = IDL.plot(x + 90, y, 'b-o2', overplot=1)
>>> m.save('map.png', resolution=96, border=0, transparent=1)
Notice that any output from IDL gets printed out in the Python console.
Execute the same commands, but called directly within the IDL interpreter:
>>> IDL.run("arr = findgen(100)/50*3.14159")
>>> IDL.run("help, arr", stdout=1)
ARR FLOAT = Array[100]
>>> IDL.run("x = 50*sin(arr)")
>>> IDL.run("y = 50*cos(arr)")
>>> IDL.run("m = map(/test)")
>>> IDL.run("p = plot(x - 90, y, 'r-o2', /overplot)")
>>> IDL.run("p = plot(x + 90, y, 'b-o2', /overplot)")
>>> IDL.run("m.save, 'map.png', resolution=96, border=0, /transparent")
Import the IDL Module
To start using the IDL module from within Python, you can use the following command:
>>> from idlpy import *
At this point you now have access to all of the methods on the IDL class.
IDL.run
The IDL.run method executes IDL commands within the IDL interpreter. Any output produced by IDL is either returned in the result or redirected to the Python console.
Examples
Execute some arbitrary IDL code and print the result:
>>> IDL.run('arr = FINDGEN(100)')
>>> IDL.run('help, arr', stdout=1)
ARR FLOAT = Array[100]
Execute multiple IDL statements using the "&" operator:
>>> result = IDL.run('for i=0,9 do begin & print, i & endfor')
>>> print(result)
0
1
...
9
Syntax
Result = IDL.run( command [, stdout=False] [, silent=False] )
Return Value
By default the return value is a Python string containing all of the IDL output. If stdout is set to True then all of IDL's output is redirected to the Python console and the return value is None.
Arguments
Command
A string containing the IDL statements to execute in the IDL interpreter. You can send a multi-statement command by using a single string and separating the statements with the IDL "&" operator.
Keywords
stdout
Set this keyword to True to redirect all of IDL's output to the Python console.
silent
Set this keyword to True to avoid saving the command to IDL's command history.
Additional Information on the idlpy.IDL Class
Calling IDL Routines
Once you have imported the idlpy module, you can call any function or procedure on IDL's path using the "dot" notation. Arguments and keywords can be passed to the routine. For example:
>>> from idlpy import *
>>> arr = IDL.randomu(None, 10000)
>>> arr = IDL.smooth(arr, 50)
>>> spec = IDL.fft_powerspectrum(arr, 0.1)
% Compiled module: FFT_POWERSPECTRUM.
>>> import matplotlib.pyplot as plt
>>> plt.semilogy(spec)
>>> plt.show()
This creates the figure shown above.
IDL Output Arguments and Keywords
Because Python does not let you modify arguments, you cannot call IDL routines that return values as named arguments or keywords. For example, you could not directly call the TRIANGULATE routine (using IDL.triangulate) since it returns its result in the third argument. In these cases use the IDL.run method and then retrieve the result from IDL using the Python attribute notation:
>>> from idlpy import *
>>> import numpy.random as ran
>>> x = ran.rand(10)
>>> y = ran.rand(10)
>>> IDL.x = x
>>> IDL.y = y
>>> IDL.run('Triangulate, x, y, triangles')
>>> tri = IDL.triangles
>>> tri
array([[1, 3, 4],
[1, 4, 9],
[1, 9, 8],
...
IDL Object Classes
If you have retrieved an object from IDL, that object will be wrapped in an idlpy.IDL class. You can then call methods or get and set properties on that object by using the "dot" notation. For example, we could construct an IDL graphics plot, modify some properties on the plot, and then save the plot to a file:
>>> from idlpy import *
>>> import numpy.random as ran
>>> arr = ran.rand(100)
>>> p = IDL.plot(arr, title='My Plot')
>>> print(p)
idlpy.IDL <92279472> IDL Class: PLOT <HVID=9727>
>>> p.color = 'red'
>>> p.save('myplot.pdf')
>>> p.close()
Case Sensitivity
IDL variable and method names are case insensitive while Python names are case sensitive. When you call an IDL function or method, such as the save method on the IDL PLOT class, the bridge will automatically convert the name to uppercase before asking IDL for the routine.
Passing Variables to and from IDL
Normally, you will pass Python variables into IDL function calls as input arguments or keywords, and receive the result back as an Python variable. However, if you use the IDL.run method, you may want to pass variables to or from IDL directly. To do this, you can use the standard Python attribute notation on the IDL class. For example:
Set an IDL variable
>>> from idlpy import *
>>> import numpy.random as ran
>>> arr = ran.rand(5)
>>> IDL.arr = arr # pass by value
>>> IDL.run('print, arr')
0.64949746 0.42264582 0.54525948 0.54869483 0.97396999
Retrieve an IDL variable
>>> from idlpy import *
>>> IDL.run('arr2 = FINDGEN(10,20,30)')
>>> arr2 = IDL.arr2 # pass by value
>>> arr2.shape
(30, 20, 10)
Note: All variables that are passed from IDL back to Python will be given a lowercase name.
Tip: For more information on passing variables see Python Bridge: Parameter Passing and Data Conversion.
Retrieving IDL System Variables
To retrieve an IDL system variable such as !DPI or !CONST, you can use the Python getattr() method:
>>> from idlpy import *
>>> getattr(IDL, "!dpi")
3.1415926535897931
>>> const = getattr(IDL, "!const")
>>> const.keys()
dict_keys(['ALPHA', 'AU', 'C', 'DTOR', 'E', 'EPS0', 'EULER', 'F', 'G', 'GN', 'H', 'HBAR', 'I', 'K', 'LY', 'M_EARTH', 'M_SUN', 'ME', 'MN', 'MP', 'MU0', 'N0', 'NA', 'P0', 'PARSEC', 'PHI', 'PI', 'R', 'R_EARTH', 'RTOD', 'RE', 'RYDBERG', 'SIGMA', 'T0', 'U', 'VM'])
>>> const['PARSEC']
30856775814671912.0
Error Handling and Exceptions
If IDL encounters a syntax or runtime error while executing your code, then the Python bridge will issue an IDLError exception and halt execution of your Python script. If desired, you could use a "try/except" within your Python code to handle these errors.
For example, if you have an IDL syntax error:
>>> from idlpy import *
>>>IDL.run('print, 2+')
Traceback (most recent call last)
...
idlpy.IDLError:
print, 2+
^
% Syntax error.
To catch an IDL error within a script:
try:
IDL.run(mycommand)
except IDLError as e:
print('Caught IDL error: ' + str(e))
else:
print('IDL command succeeded')
Version History
8.5 |
Introduced |
8.6 |
Added error handling and IDLError exception
|
See Also
!NULL, HASH, LIST, IDL to Python Bridge (PYTHON class), Python Bridge Parameter Passing and Data Conversion