Skip to content

pencil.backpack

Illa edited this page Feb 24, 2021 · 1 revision

pencil.backpack package

Submodules

pencil.backpack.in_ipynb module

pencil.backpack.in_ipynb.in_ipynb()

Returns True if executed in jupyter notebook, else False.

pencil.backpack.module_exists module

pencil.backpack.module_exists.module_exists(MOD)

Returns True if module MOD exists, else False.

pencil.backpack.pidly module

pIDLy 0.2.7: IDL within Python.

Control ITT’s IDL (Interactive Data Language) from within Python.

https://github.com/anthonyjsmith/pIDLy http://pypi.python.org/pypi/pIDLy/

Requirements:

  • Pexpect

  • NumPy

Usage:

>>> import pidly
>>> idl = pidly.IDL()

print(idl.doc)

Consult the docstrings or README.txt in the source distribution for further information.

Copyright (c) 2008-2017, Anthony Smith anthonysmith80@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class pencil.backpack.pidly.IDL(*arguments, **kwargs)

Bases: pexpect.pty_spawn.spawn

pidly.IDL() : Launch IDL session within Python.

The IDL class inherits from pexpect.spawn. Consult pexpect documentation for details of further methods.

Usage:

Initiate:

import pidly idl = pidly.IDL()

Or:

idl = pidly.IDL(‘/path/to/idl’)

Execute commands:

idl(‘x = total([1, 1], /int)’)

Retrieve values:

print(idl.ev(‘x’)) 2

Or (slightly slower):

print(idl.x) 2

Evaluate expressions:

print(idl.ev(‘x ^ 2’)) 4

Use cache (IDL save) to handle large arrays:

idl(‘x=[1,2,3,4,5,6]’) print(idl.ev(‘x’, use_cache=True)) [1 2 3 4 5 6]

Transfer a list of IDL variables, using cache:

idl(‘y=[1,2,3,4,5,6]’) xy = idl.ev_list([‘x’,’y’], use_cache=True) print(sorted(xy.keys())) [‘x’, ‘y’] print(xy[‘x’]) [1 2 3 4 5 6]

Assign value from Python expression:

idl.x = 2 + 2 print(idl.x) 4

Or:

idl(‘x’, 2 + 2) print(idl.x) 4

Perform IDL function on Python expression(s):

idl.func(‘reform’, range(4), 2, 2) array([[0, 1],

[2, 3]])

Or (slightly slower):

idl.reform(range(4), 2, 2) array([[0, 1],

[2, 3]])

With keywords (/L64 -> L64=True or L64=1)

x = idl.histogram(range(4), binsize=3, L64=True) print(x) [3 1] print(x.dtype) int64

IDL procedure with Python argument(s):

idl.pro(‘plot’, range(10), range(10), xstyle=True, ystyle=True)

Interactive mode:

idl.interact() IDL> print, x

4

IDL> ^D

Close:

idl.close()

pIDLy supports the transfer of: * ints, longs, … * floats, doubles, … * strings * arrays of the above types, with arbitrary size and shape * dictionaries <-> structures & lists of dicts <-> arrays of structures

but with certain limitations on transfer from Python to IDL

[NB if getting Syntax Errors when passing large arrays to IDL, try using

idl = pidly.IDL(long_delay=0.05) default is 0.02.]

close()

Close IDL session.

Try to call IDL exit function - this way you may still be able to terminate IDL if it is a called indirectly through a script.

ev(expression, print_output=True, use_cache=None)

Return the value of an IDL expression as a numpy.ndarray.

ev_list(names, print_output=True, use_cache=None)

Return a dictionary containing values of IDL variables in list names.

ex(expression, assignment_value=None, print_output=True, ret=False)

Execute a command in IDL.

If assignment_value is set (to a Python expression), this value is assigned to the IDL variable named in expression.

func(name, *args, **kwargs)

Evaluate IDL function.

interact(show_prompt=True, **kwargs)

Interactive IDL shell. Press ^D to return to Python.

This gives control of the child process to the interactive user (the human at the keyboard). Keystrokes are sent to the child process, and the stdout and stderr output of the child process is printed. This simply echos the child stdout and child stderr to the real stdout and it echos the real stdin to the child stdin. When the user types the escape_character this method will return None. The escape_character will not be transmitted. The default for escape_character is entered as Ctrl - ], the very same as BSD telnet. To prevent escaping, escape_character may be set to None.

If a logfile is specified, then the data sent and received from the child process in interact mode is duplicated to the given log.

You may pass in optional input and output filter functions. These functions should take a string and return a string. The output_filter will be passed all the output from the child process. The input_filter will be passed all the keyboard input from the user. The input_filter is run BEFORE the check for the escape_character.

Note that if you change the window size of the parent the SIGWINCH signal will not be passed through to the child. If you want the child window size to change when the parent’s window size changes then do something like the following example:

import pexpect, struct, fcntl, termios, signal, sys
def sigwinch_passthrough (sig, data):
    s = struct.pack("HHHH", 0, 0, 0, 0)
    a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
        termios.TIOCGWINSZ , s))
    if not p.closed:
        p.setwinsize(a[0],a[1])

# Note this 'p' is global and used in sigwinch_passthrough.
p = pexpect.spawn('/bin/bash')
signal.signal(signal.SIGWINCH, sigwinch_passthrough)
p.interact()

pro(name, *args, **kwargs)

Execute IDL procedure.

variables()

Return list of names of defined IDL variables.

exception pencil.backpack.pidly.IDLInputOverflowError()

Bases: Exception

Expression too long for IDL to receive.

class pencil.backpack.pidly.TestPidly(methodName='runTest')

Bases: unittest.case.TestCase

Unit tests for pIDLy.

sendAndReceive(x)

setUp()

Hook method for setting up the test fixture before exercising it.

tearDown()

Hook method for deconstructing the test fixture after testing it.

test_100_dicts_float32_double_string()

test_20_function_calls()

test_20_function_calls_explicit()

test_20_function_calls_really_explicit()

test_2d_int_array()

test_3_3_element_dicts()

test_3_element_dict()

test_3d_int_array()

test_3d_list_of_strings()

test_4d_int_array()

test_50_doubles()

test_50_doubles_1e30()

test_50_float32()

test_50_float32_1e30()

test_6d_int_array_tests_max_n_elements_code_area()

test_8d_int_array()

test_dict_string_arrays()

test_ev_list()

test_ev_list_with_cache()

test_ev_with_cache()

test_huge_double()

test_idl_dead()

test_inf_nan_array()

test_infinity()

test_infinity_neg()

test_int_array()

test_list_of_strings()

test_long_function_call()

test_long_function_dicts()

test_long_int_array()

test_long_integer()

test_longest_line()

test_longest_string()

test_longest_string_overflow()

test_longish_function_call()

test_mixed_array_warning()

test_multi_word_string()

test_nan()

test_simple_dictionary()

test_single_element_list_int()

test_single_float()

test_single_float32()

test_single_integer()

test_single_string()

test_speed_20000_doubles()

test_speed_5000_doubles_one_by_one()

pencil.backpack.pidly.close_all()

pencil.backpack.pidly.now()

Returns new datetime object representing current time local to tz.

tz

Timezone object.

If no tz is specified, uses local timezone.

pencil.backpack.pidly.test()

Run full tests on pIDLy.

pencil.backpack.printProgressBar module

pencil.backpack.printProgressBar.printProgressBar(iteration, total, pbar=False, prefix='', suffix='', decimals=1, length=50, fill='X', verbose=False)

Call in a loop to create terminal progress bar

  • Parameters

    • - Required (total) – current iteration (Int)

    • - Required – total iterations (Int)

    • - RECOMMENDED (pbar) – put progress bar object here, False initially

    • - Optional (fill) – prefix string (Str)

    • - Optional – suffix string (Str)

    • - Optional – positive number of decimals in percent complete (Int)

    • - Optional – character length of bar (Int)

    • - Optional – bar fill character (Str)

Example

pbar = False; Nt = np.size(varlist) for ii, varname in enumerate(varlist):

pbar = pcn.backpack.printProgressBar(ii, Nt, pbar=pbar) var = pcn.read.var(varname, trim_all=True) …

Non-tqdm Example:

printProgressBar(i, l, prefix = ‘Progress:’, suffix = ‘Complete’, length = 50)

Credit: Greensticks modified version of @Vladimir Ignatyev’s solution

[http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console](http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console)

Module contents

Clone this wiki locally