././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1713914522.5577576 pyorick-1.5/0000775000175000017500000000000000000000000012722 5ustar00davedave00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1675877106.0 pyorick-1.5/DESCRIPTION.rst0000664000175000017500000003131100000000000015236 0ustar00davedave00000000000000Run Yorick from Python ====================== The pyorick package starts `yorick `_ as a subprocess and provides an interface between python and yorick interpreted code. Interface to yorick from python ------------------------------- You can launch yorick as a subprocess with:: from pyorick import * yo = Yorick() You can execute yorick code, or evaluate a yorick expression like this:: yo('code') v = yo('=expr') However, the main way to interact with yorick is through one of three handles:: chandle = yo.call ehandle = yo.evaluate vhandle = yo.value These may be abbreviated to their first character: ``yo.c`` for ``yo.call``, or ``yo.e`` for ``yo.evaluate``, or ``yo.v`` for ``yo.value``. Attributes of any of the three handle objects represent yorick variables. Use the value handle to immediately set or get a whole variable values from yorick:: yo.v.varname = yo.v.varname The data passed to yorick by setting an attribute, or retrieved from yorick by getting an attribute can be any numeric or string scalar or array, or an index range (slice in python), or nil (None in python), or an oxy object whose members are all supported data types. The oxy object in yorick will be a list in python if all its members are anonymous, and a dict in python if all its members have names. Yorick numeric scalars or arrays become python numpy arrays. Yorick scalar strings become python unicode strings, while yorick arrays of strings become nested lists of python unicode strings. Yorick strings are encoded and decoded as iso_8859_1 python character sequences, and only the part of a python string up to the first ``'0x00'`` character, if any, is transmitted to yorick. Pyorick does not support yorick struct instances and pointers, nor python class instances. The call and evaluate handles are primarily intended for referring to yorick functions. Unlike python, yorick has two syntaxes for invoking functions:: funcname, arglist funcname(arglist) The first form invokes funcname as a subroutine, discarding any return value, while the second invokes funcname as a function, returning its value. Yorick functions frequently have return values, even if they are usually intended to be invoked as subroutines. Hence, a python interface to yorick needs separate call and evaluate handles to allow for the fact that python has only a single syntax for invoking a function. Thus:: yo.c.funcname(arglist) invokes the yorick funcname as a subroutine, discarding any return value, while:: yo.e.funcname(arglist) invokes the yorick funcname as a function, returning its value. The arglist may include either positional or keyword arguments or both:: yo.c.plg(y, x, color='red') 4 * yo.e.atan(1) The evaluate and call handle attributes do not communicate with yorick (unlike the value handle attributes, which do). Instead, they return references to yorick variables. Thus, ``yo.c.plg`` is a call-semantics reference to the yorick variable ``plg``, while ``yo.e.atan`` is an eval-semantics handle to the yorick variable ``atan``. The communication with yorick only occurs when you call the reference, as in the examples. To kill a running yorick, you can use any of these:: yo.c.quit() yo('quit') yo.kill() The last tries the quit command first, then sends SIGKILL to the process if that doesn't work. Variable references can be useful for data variables as well as for function variables. In particular, you may want to query the data type and shape of a variable without actually transferring its data. Or, if you know a variable is large, you may want to set or get only a slice, without transferring the entire array. You can do those things with an eval-sematics handle instead of a value-semantics handle:: yo.e.varname.info yo.e.varname[indexlist] = yo.e.varname[indexlist] The info property is an integer array with info[0] a data type code, and for array types info[1] is the rank, and info[2:2+rank] are the dimension lengths in yorick order. The indexlist also has yorick index semantics (first index varies fastest in memory, 1-origin indices, slices include their stop value). The call handle attempts to convert indexlist from python index list semantics (first index slowest, 0-origin, slice stop non-inclusive) in yo.c.varname[indexlist], but you are better off sticking with yorick semantics if you possibly can. Finally, you can read the whole value from a reference using:: yo.e.varname.value # or, if you prefer: yo.e.varname.v Additional properties are available to test for specific types of data, as a convenience in lieu of the general info property, all without transferring the object itself:: is_string is_number is_bytes is_integer is_real is_complex shape # tuple for numpy.ndarray or None if not array is_func is_list is_dict is_range is_nil is_obj is_file # 0 if not, 1 if binary, 2 if text In general, you can switch from any type of reference to any other by getting the c, e, or v (or call, evaluate, or value) attribute. For example, ``yo.e.varname.c`` is the same as ``yo.c.varname``. A few attribute names are reserved for use by python (e.g.- ``__init__``), and so cannot be accessed. If you need them, you can use the alternate syntax ``yo.e['funcname']`` or ``yo.c['funcname']`` or ``yo.v['varname']`` wherever you wanted ``yo.e.funcname``, etc. This syntax is also useful when the yorick variable name is stored in a python variable. As a special case, an empty string item of any handle returns the original top-level yorick process object. For example, ``yo.v['']`` returns ``yo``. You can also call any of the three handles as a function, passing it yorick code or an expression (the same as the top-level yo object). When using the evaluate handle, you don't need the "=" prefix to return an expression value:: yo.e("expr") # same as yo("=expr") yo.c("code") # discards any return value, like yo("code") Although pyorick cannot pass non-array data between python and yorick (except dict or list aggregates), it does provide you with a means for holding references to yorick values in a python variable. For example, the yorick createb function returns a file handle, which cannot be transmitted to python. However, when you ask pyorick to evaluate an expression which returns an object it cannot transmit, it returns instead a reference to the object. You can pass such a reference back to yorick as a function argument. For example, you can create a file, save something to it, and close the file like this:: f = yo.e.createb("myfile.pdb") yo.c.save(f, test=[1.1, 1.2, 1.3]) del f # destroying the python reference closes the file As a side effect, these python reference objects permit you to easily and naturally create yorick variables holding non-transmittable objects:: yo.e.f = yo.e.createb("myfile.pdb") yo.c.save(yo.e.f, test=[1.1, 1.2, 1.3]) yo.c.close(yo.e.f) Without reference objects, the first line would fail -- the createb call returns a reference object to python, which python passes back to yorick redefining the yorick f symbol. Between the first and second lines of this python code, python discards the reference object, which sends an implicit command back to yorick removing the original return value of the createb function, leaving f in yorick as the sole reference to the file. These reference objects differ from the objects returned by the evaluate or call handles. The latter merely hold the name of a yorick variable, requiring no communication with yorick at all. The former hold an index into a list of references yorick holds, for values with do not (necessarily) belong to any yorick variable, like the result of an expression. As we just described, references are created automatically to hold any expression with an unsupported datatype. You can also force yorick to return a reference value, even when an expression or a function result could be transmitted:: ref1 = yo.e("@expr") # evaluate expr, return reference to result ref2 = yo.e.fun.hold(args) # return reference to fun(args) ref3 = yo.e.ary.hold[indexs] # return reference to ary(indexs) Note that ref1, ref2, or ref3 is only useful to pass back to yorick as a value, an argument, or an index. In the (unlikely) event that the reference is a function, it has evaluate semantics by default. You can get call semantics or hold-reference sematics like this:: ref1(args) # call ref1 as function, return result ref1.call(args) # call ref1 as subroutine, discard result ref1.hold(args) # call ref1 as function, return reference to result Going in the other direction, when you try to send a non-encodable python object to yorick (as a variable value or a function argument, for example), pyorick will pickle it if possible. It then sends the pickled object as a 1D array of type char, beginning with ``'thisispickled_'`` plus the md5sum of ``'thisispickled\n'``. Conversely, if pyorick receives a 1D char array beginning with this prefix, it unpickles the bytes and returns the resulting object. Thus, although yorick cannot interpret such objects, it can, for example, store them in save files, which will make sense when pyorick reads them back. You can turn this behavior off by calling ``ypickling(False)`` or back to the default on state with ``ypickling(True)``. Interface to python from yorick ------------------------------- Pyorick can also turn python into a terminal emulator for yorick:: yo() returns a yorick prompt, at which you can type arbitrary yorick commands. The py function in yorick returns you to the python prompt if invoked as a subroutine, or execs or evals python code if passed a string:: py; // return to python prompt py, "python code"; py, ["python code line 1", "python code line 2", ...]; py("python expression") Any python code or expression is evaluated in the namespace of the python ``__main__`` program (not, for example, in the pyorick module). (You can set the variable ``server_namespace`` in the pyorick module to another namespace -- either a module or a dict -- before you create a Yorick instance if you want something other than ``__main__`` to be the namespace for these expressions.) Additional arguments to the py function cause the expression in the first argument to be called as a function in python, returning its value, or discarding any return value if invoked as a subroutine:: py, "callable_expr", arg1, arg2; py("callable_expr", arg1, arg2) A postfix ``":"`` or ``"="`` at the end of the expression permits you to set python variable values, or to get or set array slices:: py, "settable_expr=", value; # settable_expr = value py("array_expr:", i1, i2) # array_expr[i1, i2] py, "array_expr:", i1, i2, value; # array_expr[i1, i2] = value Additional features ------------------- Finally, some minor features or pyorick are worth mentioning: 1. The boolean value of most pyorick objects, such as ``yo``, ``yo.e``, or ``yo.e.name``, is True if and only if the underlying yorick process is alive. 2. The function ``yencodable(value)`` returns True if and only if the python value can be sent to yorick (without pickling). 3. For any of the top-level object or handle object function calls, you may supply additional arguments, which will be interpreted as format arguments:: yo(string, a, b, c) # same as yo(string.format(a,b,c)): yo.c("""func {0} {{ {1} }} """, name, body) # note {{ ... }} becomes { ... } 4. Two special objects can be used in data or arguments passed to yorick:: ystring0 ynewaxis The former looks like '' to python, but will be interpreted as string(0) (as opposed to "") in yorick. The latter is the yorick pseudo-index -, which is np.newaxis in python. Unfortunately, np.newaxis is None in python, which is [] in yorick, and interpreted as : in the context of an index list. 5. All pyorick generated errors use the ``PYorickError`` class. There is currently no way to handle yorick errors (and continue a yorick program) in python, although the yorick error message will be printed. Trying to send an unpicklable object to yorick will raise ``PicklingError``, not ``PYorickError``. In terminal emulator mode, pyorick catches all python errors, ignoring them in python, but returning error indications to yorick as appropriate. 6. The ``Key2AttrWrapper`` function wraps a python object instance, so that its get/setitem methods are called when the get/setattr methods of the wrapped instance are invoked. You can use this to mimic yorick member extract syntax in python objects which are references to yorick objects, struct instances, or file handles. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1675877106.0 pyorick-1.5/LICENSE.txt0000664000175000017500000000245000000000000014546 0ustar00davedave00000000000000Copyright (c) 2014, David H. Munro and John E. Field All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1675877106.0 pyorick-1.5/MANIFEST.in0000664000175000017500000000013200000000000014454 0ustar00davedave00000000000000include pyorick/pyorick.i0 include README.rst include DESCRIPTION.rst include LICENSE.txt ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1713914522.5577576 pyorick-1.5/PKG-INFO0000644000175000017500000000310300000000000014012 0ustar00davedave00000000000000Metadata-Version: 2.1 Name: pyorick Version: 1.5 Summary: python connection to yorick Home-page: https://github.com/dhmunro/pyorick Author: David Munro and John Field Author-email: dhmunro@users.sourceforge.net License: http://opensource.org/licenses/BSD-2-Clause Platform: Linux Platform: MacOS X Platform: Unix Classifier: License :: OSI Approved :: BSD License Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Operating System :: POSIX :: Linux Classifier: Operating System :: MacOS :: MacOS X Classifier: Operating System :: Unix Classifier: Topic :: Scientific/Engineering Classifier: Topic :: Software Development :: Interpreters Requires: numpy License-File: LICENSE.txt Run Yorick from Python ====================== The pyorick package starts `yorick `_ as a subprocess and provides an interface between python and yorick interpreted code. Features: - exec or eval arbitrary yorick code strings - get or set yorick variables - call yorick functions or subroutines with python arguments - get or set slices of large yorick arrays - terminal mode to interact with yorick by keyboard through python Most of the data is exchanged via binary pipes between the two interpreters. Yorick runs in a request-reply mode. Python prints anything yorick sends to stdout or stderr except prompts. See `DESCRIPTION.rst `_ for a complete description of the interface. You can clone or fork https://github.com/dhmunro/pyorick to contribute to pyorick. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1675877106.0 pyorick-1.5/README.rst0000664000175000017500000000153700000000000014417 0ustar00davedave00000000000000Run Yorick from Python ====================== The pyorick package starts `yorick `_ as a subprocess and provides an interface between python and yorick interpreted code. Features: - exec or eval arbitrary yorick code strings - get or set yorick variables - call yorick functions or subroutines with python arguments - get or set slices of large yorick arrays - terminal mode to interact with yorick by keyboard through python Most of the data is exchanged via binary pipes between the two interpreters. Yorick runs in a request-reply mode. Python prints anything yorick sends to stdout or stderr except prompts. See `DESCRIPTION.rst `_ for a complete description of the interface. You can clone or fork https://github.com/dhmunro/pyorick to contribute to pyorick. ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1713914522.5577576 pyorick-1.5/pyorick/0000775000175000017500000000000000000000000014402 5ustar00davedave00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1675877106.0 pyorick-1.5/pyorick/__init__.py0000664000175000017500000002362200000000000016520 0ustar00davedave00000000000000# make this package act like a single module # - it is a package in order to be easily grouped with pyorick.i0 in setup.py """Interface to a yorick process. See the DESCRIPTION.rst file in the pyorick source distribution for more detailed explanations. yo = Yorick() start a yorick process yo('code') execute code in yorick, return None v = yo('=expr') execute expr in yorick, return value yo.v or yo.value value-semantics handle yo.e or yo.evaluate evaluate-semantics handle yo.c or yo.call call-semantics handle yo.v[''] or yo.e[''] or yo.c[''] return a copy of the parent yo object yo.c('code') same as yo('code'), parses and executes code yo.e('expr') same as yo('=expr'), returns expr value yo(string, a, b, ...) or yo.e(string, a, b, ...) -shorthand for string.format(a,b,...) passed to yo or yo.e (or yo.c) yo.v.var returns value of yorick variable var yo.v.var = expr sets value of yorick variable var to expr yo.e.var=expr or yo.c.var=expr same as yo.v.var=expr yo.e.fun(arglist) returns value of yorick expression fun(arglist) yo.c.fun(arglist) calls yorick function as subroutine fun,arglist yo.e.ary[ndxlist] returns value of yorick expression ary(ndxlist) yo.c.ary[ndxlist] same, but numpy ndxlist semantics yo.e.ary[ndxlist] = expr sets yorick array slice ary(ndxlist)=expr yo.c.ary[ndxlist] = expr same, but numpy ndxlist semantics An arglist may include both positional and keyword arguments. Note that python syntax requires all keyword arguments to follow all positional arguments (although yorick syntax does not). An ndxlist is not distinguishable from an arglist in yorick, but in python there are syntactic differences: Index ranges start:stop:step are allowed in an ndxlist, but not in an arglist. A python arglist may be empty, but a python ndxlist may not be empty. The yo.e evaluate handle passes the index list as-is to yorick, where array indices begin at 1, the upper limit of an index range is inclusive, and the index order is fastest-to-slowest varying in memory. The yo.c call handle makes a crude attempt to translate ndxlist from numpy to yorick semantics by swapping the order of ndxlist and attempting to adjust the numpy 0-origin indexing and range stop semantics. This almost certainly does not work in all cases, so you are better off using the yo.e handle for array indexing. An ndxlist element may have a string value to extract a member from a yorick object: yo.e.ary['mem'] ary.mem or get_member(ary,"mem") in yorick yo.e.ary[1,'mem1',2:3,'mem2'] ary(1).mem1(2:3).mem2 in yorick Not all objects can be passed through the pipes connecting python and yorick. The expr, arglist, and ndxlist elements must be numpy arrays or array-like nested lists of elements of a common data type (convertable to numpy arrays with the numpy.array constructor). Only numeric or string arrays are permitted. Yorick strings are iso_8859_1 encoded and '\0'-terminated, so any python strings containing '\0' characters will be silently truncated at the first '\0' when transmitted to yorick, and any string which cannot be iso_8859_1 encoded will raise an exception. In addition to string or numeric arrays, a slice object or the value None can be encoded, translating as an index range or [], respectively, in yorick. Finally, a list or a string-keyed dict whose members are also encodable (including other such list or dict objects recursively). In yorick, these become oxy objects whose members are all anonymous (for a list) or all named (for a dict). yo.c.quit() quit yorick (by invoking yorick quit function) yo.kill() try yo.c.quit(), then SIGKILL if that doesn't work bool(yo), bool(yo.e), bool(yo.v), bool(yo.e.var), etc. True if yorick process is alive, False if it has quit or been killed yo.v['var'] or yo.e['var'] or yo.c['var'] same as yo.v.var, yo.e.var, or yo.c.var, respectively -work for otherwise reserved python attribute names (e.g.- __init__) -useful when yorick variable name is stored in python variable Given yo.e.var or yo.c.var, you can switch to any other handle type, for example: var = yo.c.var var.v or var.value same as yo.v.var, immediately returns value var.e(arglist) returns yorick var function value var(arglist) var = yo.e.var var.v or var.value same as yo.v.var, immediately returns value var.c(arglist) calls yorick var as subroutine var,arglist var = yo.e.var (or = yo.c.var) var.info return [typeid,rank,shape] var.shape return numpy.ndarray shape tuple, or None if not array Tests for encodable objects: var.is_string var.is_number var.is_bytes var.is_integer var.is_real var.is_complex var.is_range var.is_nil var.is_list var.is_dict Tests for non-encodable objects: var.is_func var.is_obj yorick oxy object with both anonymous and named members var.is_file yorick file handle, 0 = not file, 1 = binary, 2 = text When a yorick variable has an unencodable value, yo.v.var produces the same python object as yo.c.var. The call or evaluate semantic variable objects are simply references to the yorick variable var. If that variable is changing in yorick, yo.e.var or yo.c.var always refers to the value of var at the time python does something using the object. You may also pass yo.e.var or yo.c.var as an element of an arglist or an ndxlist to have yorick place var in the list, without transmitting its value to python and back (as would happen if you placed yo.v.var in an arglist or ndxlist). When a yorick function returns a non-encodable object, pyorick holds a use (in yorick) of that object, and returns a reference to that use to python. For example: f = yo.e.createb('myfile.pdb') returns a reference f to a use of the yorick file handle returned by the yorick create function. The python object f is similar to the reference object yo.e.f, but in this case, there is no yorick variable corresponding to the object. You can pass the python f to a yorick function, for example yo.c.save(f, item=[1,2,3]) save [1,2,3] as item in myfile.pdb f['item'] return value of item in myfile.pdb When the python object f is destroyed, its destructor removes the (only) use of the corresponding yorick object. In the case of yorick file handles, this closes the file: del f Held-reference objects like f are evaluate-semantics variable handles. You can also hold a use of an encodable yorick object, if you do not want to pass its value back to python, and you do not want to create a yorick variable to hold its value: yo.e('@expr') do not transmit value, hold&return use of result -passes additional arguments format method of first, as usual yo.e.fun.hold(arglist) fun(arglist), but hold&return use of result yo.e.ary.hold[ndxlist] fun(arglist), but hold&return use of result Any held-reference object has a value attribute and the various query attributes, like ordinary reference-by-name objects: x = yo.e.random.hold(100,100,1000) # 1e7 numbers held in yorick y = x.v # or x.value, transmits 1e7 numbers to python y = numpy.zeros(x.shape) # make python array of same shape as x By default, held-reference objects have evaluate-semantics. You can get call semantics with x.call(arglist) as usual. You can also hold the result of a function call or slice with x.hold(arglist) or x.hold[ndxlist]. When you try to send a non-encodable python object to yorick (as a variable value or a function argument, for example), pyorick will pickle it if possible. It then sends the pickled object as a 1D array of type char, beginning with 'thisispickled_' plus the md5sum of 'thisispickled\n'. Conversely, if pyorick receives a 1D char array beginning with this prefix, it unpickles the bytes and returns the resulting object. Thus, although yorick cannot interpret such objects, it can, for example, store them in save files, which will make sense when pyorick reads them back. You can turn this behavior off by calling ypickling(False) or back to the default on state with ypickling(True). (The pickling behavior lives in the pyorick pipeline codec, not in the yorick process handles.) The following special objects are available for use in expressions used to set variable values in yorick: ystring0 yorick string(0) is C NULL, different than "" ynewaxis np.newaxis is None, which yorick interprets as : The ystring0 value is also passed back to python to represent a string(0) value in yorick. It is derived from str and has value '' in python. You can check for it with "s is ystring0" if you need to distinguish. Pyorick also provides a Key2AttrWrapper function that wraps an object instance so that its get/setitem methods are called when the get/setattr methods of the wrapped instance are invoked. You can use this to mimic yorick member extract syntax in python objects which are references to yorick objects, struct instances, or file handles. All pyorick generated errors use the PYorickError exception class, although PicklingError may be raised if pickling fails. Finally, pyorick can turn the python command line into a yorick terminal: yo() enter yorick terminal mode, special yorick commands are: py from yorick terminal mode returns to python py, "code" from yorick terminal mode to exec code in python py("expr") from yorick terminal mode to eval expr in python py, "expr=", value sets python expr to value py("expr", arg1, arg2, ...) returns python expr(arg1,arg2,...) py("expr:", ndx1, ndx2, ...) returns python expr[ndx1,ndx2,...] py, "expr:", ndx1, ..., value sets python expr[ndx1,...]=value By default, python expressions are evaluated in the context of __main__, not in the context of the pyorick module. Python errors in terminal mode are caught and ignored by python, but will raise an exception in yorick. """ from .pyorick import * # limit names exported by "from pyorick import *" __all__ = ['Yorick', 'PYorickError', 'Key2AttrWrapper', 'ynewaxis', 'ystring0', 'yencodable', 'ypickling'] ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1675877106.0 pyorick-1.5/pyorick/pyorick.i00000664000175000017500000006517500000000000016332 0ustar00davedave00000000000000/* pyorick.i0 * run yorick as a subprocess of python * Copyright (c) 2014, David H. Munro and John E. Field * All rights reserved. * This is Open Source software, released under the BSD 2-clause license, * see http://opensource.org/licenses/BSD-2-Clause for details. */ /* This script normally runs from the command line: * yorick -i pyorick.i0 RFD WFD ... * yorick -batch pyorick.i0 RFD WFD ... * where * RFD is the read file descriptor number and * WFD is the write file descriptor number * Binary messages from python to yorick flow through RFD pipe, while * binary messages from yorick to python flow through the WFD pipe. * You may also set _pyorick_rfd and _pyorick_wfd by hand before invoking * this script for debugging purposes. */ local pyorick_dir; /* DOCUMENT pyorick_dir * Directory containing pyorick.i0, the pyorick installation directory. */ pyorick_dir = current_include(); pyorick_dir = strpart(pyorick_dir, strgrep(".*/", pyorick_dir)); func pyorick(mode) /* DOCUMENT pyorick * pyorick, mode * With no argument, receives active message from python-to-yorick * pipe, performs the requested action, and sends the response to * the yorick-to-python pipe. * With the MODE argument, switches from one-shot mode to idler mode. * MODE=0 is idler mode (the initial state if this file included from * the command line), the only communication channel is through the * python-yorick pipes; yorick ignores stdin, and installs an idler * which continues the request-response cycle indefinitely, until * the mode is set to one-shot. * MODE=1 is one-shot mode, in which only a single request-response * cycle executes. (This is the intial state if this file is not * included from the command line.) * In idler mode, yorick spends the time between request-response * cycles blocked waiting for the next request to come through the * python-to-yorick pipe. * In one-shot mode, the time between cycles is spent blocked waiting * for input from stdin, as if this were an ordinary interactive session. * If you want yorick to make screen plots, you must use one-shot mode, * because screen plots must process windowing system events, which only * happens waiting for input from stdin. * On the other hand, if you are running in unattended batch mode, * yorick quits instead of waiting for stdin, so you must use idler mode. * SEE ALSO: pydebug */ { extern _pyorick_mode, after_error; if (is_void(mode)) { local __, ___; _pyorick_hold = 0; /* hold result, set in wait/action/unparse */ if (_pyorick_wait() && _pyorick_sending && !is_void(___)) { if (pydebug) { write, "Y>pyorick request is:"; print, ___; } _pydebug = pydebug; include, grow("___=[];" , ___), 1; swap, pydebug, _pydebug; if (pydebug) { write, "Y>pyorick response is:"; info, ___; } msg = _pyorick_encode(___, 1); _pyorick_put, msg; _pyorick_sending = 0; swap, pydebug, _pydebug; if (!_pyorick_hold && is_obj(msg) && allof(msg(hdr) == [_ID_EOL,2])) save, _pyorick_refs, 3, ___; /* prepare for auto-reference */ } } else if (mode < 0) { _pyorick_mode = 1n; set_idler, , 0; after_error = []; if (pydebug) write, "Y>yorick has entered terminal mode"; } else { _pyorick_mode = (mode != 0); if (_pyorick_mode) set_idler, , 4; else set_idler, _pyorick_idler, 4; after_error = _pyorick_err_handler; if (pydebug) write, format=" Y>yorick mode = %d\n", _pyorick_mode; } } local pydebug; /* DOCUMENT pydebug = 1 * Causes debugging messages to be printed to stdout during each * request-response cycle. Set pydebug to 0 or [] to turn off * debugging messages. */ func py(arglist) /* DOCUMENT py exit pyorick terminal mode * or py, "code", arglist execute python code * or py("expr", arglist) return value of python expression * with arglist, invoke "code" or "expr" as python function * or py("vexpr:") reference python variable "vexpr" in arglist * or py("vexpr:", indexlist) return python "vexpr" slice * or py, "vexpr=", value set python "vexpr" to value * or py, "vexpr:", indexlist, value set python "vexpr" slice to value * indexlist order and meaning as in python * * Yorick API for sending active messages to python. The postfix ":" and * postfix "=" are interchangable in the last four forms. * * SEE ALSO: pyorick */ { command = arglist(1); if (is_void(command)) { /* exit yorick terminal mode */ _pyorick_send, [_ID_EOL, 0]; /* tell python to exit terminal mode */ /* write, format="%s", "ExitTerminalMode> "; */ /* pause for python to acknowledge with _ID_NIL message */ if (!is_void(_pyorick_decode(_pyorick_get()))) _pyorick_panic, "bad acknowledgement exiting yorick terminal mode"; _pyorick_mode = 1n; set_idler, , 4; after_error = _pyorick_err_handler; if (pydebug) write, "Y>py exiting yorick terminal mode"; dbexit, 0; /* return, making sure we are out of dbug> mode */ } else { nargs = arglist(0) - 1; keys = arglist(-); command = strchar(command)(1:-1); isvar = anyof(command(0) == [':','=']); if (isvar) command = command(1:-1); list = where(!command); if (numberof(list)) command(list) = '\n'; idx = hasval = 0; if (!isvar) { if (nargs || numberof(keys)) { id = am_subroutine()? _ID_SUBCALL : _ID_FUNCALL; } else { id = am_subroutine()? _ID_EXEC : _ID_EVAL; idx = 1; } } else { if (numberof(keys)) error, "python slice cannot accept keyword as index"; if (am_subroutine()) { if (!nargs) error, "set python variable requires a value"; id = (nargs>1)? _ID_SETSLICE : _ID_SETVAR; nargs -= 1; /* final argument is value, not list */ hasval = 1; } else { id = nargs? _ID_GETSLICE : _ID_GETVAR; } } if (pydebug) write, format=" Y>py id=%ld, nargs=%ld, hasval=%ld\n", id, nargs, hasval; hdr = [id, numberof(command)]; if (idx) msg = save(_pyorick_id=id, hdr, value=command); else msg = save(_pyorick_id=id, hdr, name=command); if (id == _ID_GETVAR) return msg; /* reference to python variable */ if (nargs>0 || numberof(keys)) { args = save(); for (i=1 ; i<=nargs ; ++i) save, args, string(0), _pyorick_encode(arglist(1+i), 2); for (i=1 ; i<=numberof(keys) ; ++i) { name = strchar(keys(i))(1:-1); key = save(_pyorick_id=_ID_SETVAR, hdr=[_ID_SETVAR,numberof(name)], name, value=_pyorick_encode(arglist(keys(i)), 2)); save, args, string(0), key; } save, msg, args; } if (hasval) save, msg, value=_pyorick_encode(arglist(2+nargs), 2); if (pydebug) write, "Y>py sending active request"; _pyorick_put, msg; v = _pyorick_decode(_pyorick_get()); if (pydebug) write, "Y>py decoded reply to active request"; if (is_obj(v, _pyorick_id, 1)) return v; /* ordinary passive value */ if (allof(v(hdr) == [_ID_EOL,1])) error, "python reported error"; error, "python reply undecodable"; } } wrap_args, py; /* ------------------------------------------------------------------------ */ /* remainder is not part of user interface, supports pyorick.py */ /* message id 0-15 are numeric types: * char short int long longlong float double longdouble * followed by unsigned, complex variants * passive messages (response to request): */ _ID_STRING = 16; // yorick assumes iso_8859_1, need separate id for utf-8? _ID_SLICE = 17; _ID_NIL = 18; _ID_LST = 19; _ID_DCT = 20; _ID_EOL = 21; /* active messages (passive response required): */ _ID_EVAL = 32; _ID_EXEC = 33; _ID_GETVAR = 34; _ID_SETVAR = 35; _ID_FUNCALL = 36; _ID_SUBCALL = 37; _ID_GETSLICE = 38; _ID_SETSLICE = 39; _ID_GETSHAPE = 40; /* _ID_EOL flag values: * 0 end of list * 1 error sent by _pyorick_puterr * 2 after GETVAR request to indicate unencodable * -1 yorick has quit */ /* garbled messages are fatal, shut down the pipes and exit idler loop */ func _pyorick_panic(msg) { extern _pyorick_mode; _pyorick_mode = 1n; msg = "PANIC: " + msg; if (pydebug) write, "Y>"+msg; r = _pyorick_rfd; w = _pyorick_wfd; _pyorick_rfd = _pyorick_wfd = []; if (is_array(r)) fd_close, r; if (is_array(w)) fd_close, w; error, msg; } errs2caller, _pyorick_panic; _pyorick_type = save(char, short, int, long, longlong=1, float, double, longdouble=2, uchar=char, ushort=short, uint=int, ulong=long, ulonglong=1, fcomplex=3, complex, lcomplex=4); /* make it easy to use alternative to fd_read/write pipe i/o channels */ func _pyorick_recv(x) { return fd_read(_pyorick_rfd, x); } func _pyorick_send(x) { return fd_write(_pyorick_wfd, x); } /* _pyorick_err_handler * Installed as after_error function by _pyorick_idler and pyorick,mode. * Reinstalls _pyorick_idler in idler mode. Always calls dbexit. * _pyorick_idler * Perpetual loop: Read a complete message from python, perform the * requested action, and write the response message to python. * If a python sends a passive message, raises an error (causing * _pyorick_err_handler to generate an error-EOL message). * _pyorick_wait * Called by _pyorick_idler: Wait for active message from python * by calling _pyorick_get, then call _pyorick_action to interpret * the message and generate the text of the yorick code to be * executed back in _pyorick_idler. * _pyorick_get * Read complete message from python with as little interpretation * as possible. This must be an atomic operation -- if it is * interrupted, there is no way to resynchronize the pipe, and the * whole connection must shut down. * A complete message (called msg in the code) is an oxy object; it * may contain a list of quoted messages in the case of the passive * LST/DCT messages, or the active messages which have argument or * index lists (FUNCALL, SUBCALL, GETSLICE, SETSLICE). * _pyorick_action * Thin wrapper over _pyorick_unparse to interpret active message. * _pyorick_unparse * For active messages, generate the text of the expression or statement * which causes yorick to perform the requested action. For quoted * passive messages, add their value to the stack of arguments referenced * by this text. * _pyorick_decode * Decode passive messages from the uninterpreted form returned by * _pyorick_get. Most of the work is for string array and lst/dct objects. * _pyorick_encode * Produce the passive message representing the yorick value which * is the response to the python request. The format is the same as * the output returned by _pyorick_get. Performs all the error checking * and repackaging without actually sending the response. * _pyorick_put * Send the response message to python. This must be an atomic operation; * there is no way to resynchronize the pipe, so any interruption is * fatal and causes the connection to shut down. * _pyorick_puterr * Send an error-EOL message to python, for when some error prevents * the request from being completed. */ func _pyorick_err_handler { extern _pyorick_errmsg; if (pydebug) write, "Y>_pyorick_err_handler called"; if (_pyorick_looping > 32) _pyorick_panic, "caught in exception loop\n" + (_pyorick_errmsg? _pyorick_errmsg : ""); if (_pyorick_looping < 2) _pyorick_errmsg = catch_message; if (!_pyorick_mode) set_idler, _pyorick_idler, 4; _pyorick_puterr; /* noop unless _pyorick_sending */ dbexit, 0; /* get out of debug mode from set_idler,,4 */ } _pyorick_looping = 0; func _pyorick_idler { _pyorick_looping += 1; if (pydebug) write, "Y>_pyorick_idler: enter"; for (__=___=[] ; !_pyorick_mode ; __=___=[]) pyorick; if (pydebug) write, "Y>_pyorick_idler: exit"; if (_pyorick_mode || _pyorick_looping>64) set_idler, , 4; else if (!is_void(_pyorick_rfd)) set_idler, _pyorick_idler; _pyorick_looping = 0; } func _pyorick_wait(void) { if (!is_void(_pyorick_rfd)) { if (_pyorick_sending) { if (!_pyorick_errmsg) _pyorick_errmsg = "ERROR (_pyorick_wait) "; _pyorick_puterr; _pyorick_sending = 0; } msg = _pyorick_get(1); /* atomic read */ if (pydebug) write, "Y>_pyorick_wait: got message "+print(msg(hdr))(1); if (!is_void(_pyorick_rfd)) { /* perhaps should call _pyorick_puterr if _pyorick_errmsg is set? */ _pyorick_sending = 1; if (_pyorick_action(msg)) error, "got passive message when expecting active message"; return 1n; } } return 0; } func _pyorick_refs(n, value) { if (!n) { save, _pyorick_refs, 3, value; extern ___; ___ = _pyorick_refs(1,1); } else if (am_subroutine()) { if (n>3 && n<=_pyorick_refs(*)) { /* add n to free list */ save, _pyorick_refs, noop(n), _pyorick_refs(2); save, _pyorick_refs, 2, n; } save, _pyorick_refs, 3, []; } else if (n == 1) { n = _pyorick_refs(*); if (_pyorick_refs(2) > n) { save, _pyorick_refs, 2, n+1; /* should be true without this */ for (i=1 ; i3 * _pyorick_refs(1) is above function * _pyorick_refs(2) is next free reference # * _pyorick_refs(3) is temporary value of previous result (if unencodable) * _pyorick_refs(1,1) moves 3 to next free reference #, returning that # * _pyorick_refs,1,# frees reference #, dropping use * _pyorick_refs, 1,, value * sets next free reference # to value, and sets ___ to that # */ /* slurp complete message with no excess processing -- must be atomic op * panic (close connection) if dimensions or lengths make no sense, * or if message (or quoted message) not recognized */ func _pyorick_get(ctx) { if (pydebug) write, "Y>_pyorick_get: blocking..."; hdr = _pyorick_recv([0, 0]); if (pydebug) write, "Y>_pyorick_get: got message "+print(hdr)(1); ctx = ctx && allof(hdr == [_ID_GETVAR,0]); if (!ctx) _pyorick_refs, 1, 3; /* discard previous result, if any */ id = hdr(1); msg = save(_pyorick_id=id, hdr); if (id>=0 && id<_ID_STRING) { rank = hdr(2); dims = [rank]; if (rank>0) grow, dims, _pyorick_recv(array(0, rank)); if (rank<0 || (rank && anyof(dims(1:)<=0))) _pyorick_panic, "illegal dimensions"; type = _pyorick_type(1+id); if (type == 1) { if (sizeof(long) == 8) type = long; else _pyorick_panic, "longlong unsupported"; } else if (type == 3) { type = float; dims = grow(dims(1:1)+1, 2, (dims(1)? dims(2:) : [])); } else if (is_array(type)) { _pyorick_panic, "longdouble unsupported"; } dims = _pyorick_safedims(dims); save, msg, value = _pyorick_recv(array(type, dims)); } else if (id == _ID_STRING) { rank = hdr(2); dims = [rank]; if (rank) grow, dims, _pyorick_recv(array(0, rank)); if (rank<0 || (rank && anyof(dims(1:)<=0))) _pyorick_panic, "illegal string array dimensions"; dims = _pyorick_safedims(dims); lens = _pyorick_recv(array(0, dims)); if (anyof(lens<0)) _pyorick_panic, "negative string length"; save, msg, lens; lens = sum(lens); save, msg, value = (lens? _pyorick_recv(array(char, lens)) : []); } else if (id == _ID_SLICE) { save, msg, flag = hdr(2), value = _pyorick_recv([0, 0, 0]); } else if (id == _ID_NIL) { save, msg, value = []; } else if (anyof(id == [_ID_LST, _ID_DCT])) { save, msg, value = _pyorick_getlist(); } else if (id == _ID_EOL) { save, msg, flag = hdr(2); } else if (anyof(id == [_ID_EVAL, _ID_EXEC])) { save, msg, value = _pyorick_getname(hdr(2)); } else if (anyof(id == [_ID_GETVAR, _ID_SETVAR, _ID_GETSHAPE])) { save, msg, name = (ctx? [] : _pyorick_getname(hdr(2))); if (id == _ID_SETVAR) save, msg, value = _pyorick_get(); } else if (id>=_ID_FUNCALL && id<=_ID_SETSLICE) { save, msg, name = _pyorick_getname(hdr(2)); save, msg, args = _pyorick_getlist(); if (id == _ID_SETSLICE) save, msg, value = _pyorick_get(); } else { _pyorick_panic, "unknown message id"; } return msg; } func _pyorick_safedims(dims) { rank = dims(1); while (rank > 10) { dims(1) = --rank; dims(1+rank) *= dims(2+rank); } if (numberof(dims) > 1+rank) dims = dims(1:1+rank); return dims; } func _pyorick_getname(len) { if (len <= 0) _pyorick_panic, "zero length name"; return _pyorick_recv(array(char, len)); } func _pyorick_getlist(void) { args = save(); for (;;) { m = _pyorick_get(); if (m._pyorick_id == _ID_EOL) break; save, args, string(0), m; } return args; } func _pyorick_action(msg) { id = msg(_pyorick_id); if (id < _ID_EVAL) return 1n; extern ___, __; /* command/expression string and arguments object */ __ = save(); ___ = _pyorick_unparse(msg); return 0n; } func _pyorick_unparse(msg, raw) { local value, args; id = msg(_pyorick_id); pfx = "___="; if (id < _ID_EVAL) { if (!raw) error, "expecting active message"; if (id == _ID_NIL) { txt = "[]"; } else { save, __, string(0), _pyorick_decode(msg); txt = "__(" + totxt(__(*)) + ")"; } } else if (id==_ID_EVAL || id==_ID_EXEC) { eq_nocopy, value, msg(value); isf = (id == _ID_EVAL); if (raw && !isf) error, "illegal value or argument"; list = where((value == '\n') | (value == '\r')); if (numberof(list)) value(list) = '\0'; if (!raw) { extern _pyorick_hold; _pyorick_hold = (value(1)=='\05' && numberof(value)>1); if (_pyorick_hold) { value = value(2:); pfx = "_pyorick_refs,1,,"; } } txt = strchar(value); if (isf && !raw) txt(1) = pfx + txt(1); } else if (id == _ID_GETVAR) { name = msg(name); if (raw || numberof(name)) { name = _pyorick_name(name, raw, _pyorick_hold, pfx); txt = (raw? "" : pfx) + name; } else { txt = "___=_pyorick_refs(1,1)"; } } else if (id == _ID_SETVAR) { if (raw == 3) error, "illegal keyword argument in index list"; txt = _pyorick_name(msg(name)) + "=" + _pyorick_unparse(msg(value), 1); } else if (id == _ID_GETSHAPE) { txt = pfx + "_pyorick_shape(" + _pyorick_name(msg(name)) + ")"; } else { if (raw && id!=_ID_FUNCALL) error, "illegal argument or index"; args = msg(args); /* args always an oxy object, no copy here */ n = args(*); if (id==_ID_FUNCALL || id>=_ID_GETSLICE) { name = _pyorick_name(msg(name), raw, _pyorick_hold, pfx); txt = (raw? "" : pfx) + name + "("; off = raw? 0 : strlen(pfx); } else if (id == _ID_SUBCALL) { txt = _pyorick_name(msg(name)) + (n? "," : ""); } for (i=1 ; i<=n ; ++i) { a = args(noop(i)); /* args is a msg object, no copy here */ if (id>=_ID_GETSLICE && a(_pyorick_id)==_ID_STRING) { /* immediate string index to slice operation means member extract * name( --> get_member(name,"msg")( * name(index, --> get_member(name(index),"msg")( */ s = ",\"" + _pyorick_decode(a) + "\")("; /* assume no " in string */ len = strlen(txt); if (strpart(txt, len:len) == ",") s = ")" + s; txt = streplace(txt, [off,off,len-1,len], ["get_member(", s]); } else { txt += _pyorick_unparse(a, 2+(id>=_ID_GETSLICE)); if (i < n) txt += ","; } } if (id==_ID_FUNCALL) { txt += ")"; } else if (id >= _ID_GETSLICE) { if (strpart(txt, -1:0) == ")(") txt = strpart(txt, 1:-1); else txt += ")"; if (id == _ID_SETSLICE) txt += "=" + _pyorick_unparse(msg(value), 1); } } return txt; } func _pyorick_name(name, raw, &hold, &pfx) { hold = (name(1)=='\05' && numberof(name)>1 && !raw); if (hold) { pfx = "_pyorick_refs,1,,"; name = name(2:); } ref = (name(1)<='9' && name(1)>='1'); name = strchar(name); if (ref) name = "_pyorick_refs(" + name + ")"; return name; } func _pyorick_decode(msg) { local lens, value, name; id = msg(_pyorick_id); if (id < _ID_STRING) { return msg(value); } else if (id == _ID_STRING) { eq_nocopy, lens, msg(lens); s = array(string, dimsof(lens)); list = where(lens); if (numberof(list)) s(list) = strchar(msg(value)); list = where(lens == 1); if (numberof(list)) s(list) = ""; return s; } else if (id == _ID_SLICE) { return rangeof([msg(value,1), msg(value,2), msg(value,3), msg(hdr,2)]) } else if (id == _ID_NIL) { return []; } else if (anyof(id == [_ID_LST, _ID_DCT])) { named = (id == _ID_DCT); m = msg(value); value = save(); for (i=1,n=m(*) ; i<=n ; ++i) { mi = m(noop(i)); /* mi is a message object, no copy here */ if (named) { if (mi._pyorick_id != _ID_SETVAR) error, "missing member name in dict object"; name = strchar(mi(name)); mi = mi(value); } else { name = string(0); } if (mi._pyorick_id > _ID_DCT) error, "illegal member in dict or list object"; save, value, noop(name), _pyorick_decode(mi); } return value; } else { return msg; /* other stuff is not decodable */ } } func _pyorick_shape(a) { if (structof(a) == string) id = 17 else id = where(_pyorick_type(*,) == typeof(a)); if (numberof(id)) { if (id(1) == 1) id = 9; return grow(id-1, dimsof(a)); } else if (is_func(a)) { return [-1]; } else if (is_obj(a)==3 && is_void(a._pyorick_id)) { names = a(*,); return [(noneof(names)? -2 : (allof(names)? -3 : -8))]; } else if (is_range(a)) { return [-4]; } else if (is_void(a)) { return [-5]; } else if (is_stream(a)) { return [-6]; } else if (typeof(a) == "text_stream") { return [-7]; } else { return [-9]; } } func _pyorick_encode(value, env) { if (is_obj(value, _pyorick_id, 1)) { /* ordinary passive value */ if (is_array(value)) { if (structof(value) == string) { id = 16; lens = strlen(value) + 1; dims = dimsof(lens); list = where(!value); if (numberof(list)) { if (dims(1)) lens(list) = 0; else lens = 0; value = value(where(value)); } } else { id = where(_pyorick_type(*,) == typeof(value)); if (numberof(id)) { id = id(1) - 1; if (!id) id = 8; dims = dimsof(value); } } if (numberof(id)) { msg = save(_pyorick_id=id, hdr=[id,dims(1)]); if (id != 16) save, msg, value; else save, msg, lens, value=(is_void(value)?[]:strchar(value)); } else { msg = "unencodable array datatype " + typeof(value); } } else if (is_range(value)) { id = _ID_SLICE; r = rangeof(value); msg = save(_pyorick_id=id, hdr=[id,r(4)], value=r(1:3)); } else if (is_void(value)) { msg = save(_pyorick_id=_ID_NIL, hdr=[_ID_NIL,0], value=[]); } else if (is_obj(value) == 3) { names = value(*,); named = allof(names); if (named || noneof(names)) { id = (named? _ID_DCT : _ID_LST); v = save(); msg = save(_pyorick_id=id, hdr=[id, 0], value=v); n = numberof(names); for (i=1 ; i<=n ; ++i) { m = _pyorick_encode(value(noop(i)), 0); if (!is_obj(m)) return m; if (named) { name = strchar(names(i)); m = save(_pyorick_id=_ID_SETVAR, hdr=[_ID_SETVAR,numberof(name)], name, value=m); } save, v, string(0), m; } } else { msg = "oxy object members neither all named nor all anonymous"; } } else { /* unencodable value, indicate variable reference */ msg = "unencodable value"; } if (env==1 && !is_obj(msg)) msg = save(_pyorick_id=_ID_EOL, hdr=[_ID_EOL,2], value=[]); } else { /* special or active value */ msg = "unexpected active message to python"; } if (env && !is_obj(msg)) { error, msg; } return msg; } /* send complete message with no excess processing - must be atomic op * an unknown message or other error here is a bug in _pyorick_encode */ func _pyorick_put(msg) { id = msg(_pyorick_id); if (pydebug) write, "Y>_pyorick_put: sending message "+print(msg(hdr))(1); _pyorick_send, msg(hdr); if (id < _ID_STRING) { dims = dimsof(msg(value)); if (dims(1)) _pyorick_send, dims(2:); _pyorick_send, msg(value); } else if (id == _ID_STRING) { dims = dimsof(msg(lens)); if (dims(1)) _pyorick_send, dims(2:); _pyorick_send, msg(lens); if (sum(msg(lens))) _pyorick_send, msg(value); } else if (id == _ID_SLICE) { _pyorick_send, msg(value); } else if (id == _ID_NIL) { /* hdr only */ } else if (id == _ID_LST || id == _ID_DCT) { _pyorick_putlist, msg(value); } else if (id == _ID_EOL) { /* hdr only */ } else if (id == _ID_EVAL || id == _ID_EXEC) { _pyorick_send, msg(value); } else if (id == _ID_GETVAR) { _pyorick_send, msg(name); } else if (id == _ID_SETVAR) { _pyorick_send, msg(name); _pyorick_put, msg(value); } else if (id>=_ID_FUNCALL && id<=_ID_SETSLICE) { _pyorick_send, msg(name); _pyorick_putlist, msg(args); if (id == _ID_SETSLICE) _pyorick_put, msg(value); } else if (id == _ID_GETSHAPE) { _pyorick_send, msg(name); _pyorick_put, msg(value); } else { _pyorick_panic, "unknown message id"; } if (pydebug) write, "Y>_pyorick_put: sent message "+print(msg(hdr))(1); } func _pyorick_putlist(msg) { n = msg(*); for (i=1 ; i<=n ; ++i) _pyorick_put, msg(noop(i)); _pyorick_send, [_ID_EOL, 0]; } func _pyorick_puterr { if (_pyorick_sending) { if (!is_void(_pyorick_wfd)) _pyorick_send, [_ID_EOL, 1]; _pyorick_sending = 0; } } /* parse command line to get rfd, wfd file descriptors */ _pyorick_mode = 1n; if (is_void(_pyorick_rfd)) { if (is_void(command_line)) command_line = get_argv(); /* e.g. -batch */ if (numberof(command_line) >= 2) { _pyorick_rfd = tonum(command_line(1:2)); if (allof((_pyorick_rfd>=0) & (_pyorick_rfd<1e8) & !(_pyorick_rfd%1))) { _pyorick_wfd = long(_pyorick_rfd(2)); _pyorick_rfd = long(_pyorick_rfd(1)); command_line = (numberof(command_line)>2)? command_line(3:) : []; pyorick, 0; } } } if (is_void(_pyorick_quit)) _pyorick_quit = quit; func quit(void) { /* send to both stdout and wfd in case parent blocked on either */ write, format="\n%s", "PYORICK-QUIT> "; if (!is_void(_pyorick_wfd)) _pyorick_send, [_ID_EOL, -1]; fd_close, _pyorick_wfd; fd_close, _pyorick_rfd; _pyorick_quit; } ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1698258052.0 pyorick-1.5/pyorick/pyorick.py0000664000175000017500000017332700000000000016451 0ustar00davedave00000000000000# pyorick.py # Copyright (c) 2014, David H. Munro and John E. Field # All rights reserved. # This is Open Source software, released under the BSD 2-clause license, # see http://opensource.org/licenses/BSD-2-Clause for details. # Attempt to make it work for both python 2.6+ and python 3.x. # Avoid both six and future modules, which are often not installed. #from __future__ import (absolute_import, division, # print_function, unicode_literals) # Note that these __future__ imports apply only to this module, not to # others which may import it. # In particular, under 2.x, arguments passed in to this module from callers # that do not have unicode_literals in place will generally be non-unicode. # Therefore, better to stick to the default str than to use unicode_literals. from __future__ import print_function import sys if sys.version_info[0] >= 3: basestring = str # need basestring for 2.x isinstance tests for string xrange = range # only use xrange where list might be large raw_input = input import pickle else: import cPickle as pickle import numpy as np from numbers import Number try: from collections.abc import Sequence, Mapping except ImportError: # fallback for python 2.7 or <3.3 from collections import Sequence, Mapping from ctypes import (c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong, c_float, c_double, c_longdouble, sizeof) import os import shlex import fcntl import select import subprocess import time # code executed by a yorick request runs in __main__ module by default import __main__ ######################################################################## class Yorick(object): """Interface to a yorick process. Attributes: c or call - call-semantics handle e or evaluate - eval-semantics handle v or value - value-semantics handle Handles are objects whose attributes represent yorick variables. """ def __init__(self, extra='', **kwargs): """Start a yorick process. Parameters: extra (str or list of str): additional command line arguments """ if isinstance(extra, Process): self.bare = YorickBare(extra) elif isinstance(extra, YorickBare): self.bare = extra else: self.bare = YorickBare(ProcessDefault(extra, **kwargs)) self._call = self._eval = self._value = None def __repr__(self): return "".format(repr(self.bare)[1:-1]) def __nonzero__(self): return bool(self.bare) def kill(self): """Kill yorick process.""" self.bare.proc.kill() def debug(self, on): """Set or unset debug mode for yorick process.""" self.bare.proc.debug(on) def handles(self, which=3): """Return handles whose attributes are yorick variables. Parameters: which (int, default is 3): - 1 returns call-semantics handle - 2 returns eval-semantics handle - 4 returns value-semantics handle - add to return tuple with up to three handles """ h = [['call', 'evaluate', 'value'][i//2] for i in [1, 2, 4] if (which&i)] if len(h) == 1: return getattr(self, h[0]) else: return tuple([getattr(self,h[i]) for i in range(len(h))]) # first reference creates handle, subsequent references simply use it @property def call(self): if not self._call: self._call = YorickHandle(0, self.bare) return self._call @property def evaluate(self): if not self._eval: self._eval = YorickHandle(1, self.bare) return self._eval @property def value(self): if not self._value: self._value = YorickHandle(2, self.bare) return self._value # single character abbreviations for interactive use c = call e = evaluate v = value @property def namespace(self): return self.bare._namespace @namespace.setter def namespace(self, value): if not isinstance(value, Mapping): value = value.__dict__ self.bare._namespace = value def __call__(self, command=None, *args, **kwargs): # pipe(command) """Execute a yorick command.""" return self.call(command, *args, **kwargs) # expose this to allow user to catch pyorick exceptions class PYorickError(Exception): pass # np.newaxis is None, which is [] in yorick, not - # ynewaxis provides a means for specifying yorick - in get/setslice class NewAxis(object): pass ynewaxis = NewAxis() # yorick distinguishes string(0) from an empty string; python does not # provide an empty string which can be used to pass string(0) to yorick, # but still works like an empty string in python class YString0(str): pass ystring0 = YString0() def yencodable(value): """Return True if object can be encoded for transfer to yorick.""" return codec.encode_data(value, True) def ypickling(both=None, encode=None, decode=None): """Set whether unencodable objects are pickled for transfer to yorick. Arguments: both True or False to turn pickling on or off in both directions encode turn pickling on or off in encoding direction only decode turn pickling on or off in decoding direction only Pickling is turned on in both directions by default. PYorick uses protocol 2 pickling, prepends a string beginning with 'thisispickled_', then transmits the byte string as a 1D array of char. """ if both is not None: codec.enpickle = codec.depickle = bool(both) if encode is not None: codec.enpickle = bool(encode) if decode is not None: codec.depickle = bool(decode) ######################################################################## server_namespace = __main__.__dict__ # for python code invoked by yorick class YorickBare(object): """Avoids circular references among Yorick, YorickHandle, and YorickVar.""" def __init__(self, proc): self.proc = proc self._namespace = server_namespace # default namespace (__main__) def __del__(self): self.proc.kill() def __repr__(self): return "".format(repr(self.proc)[1:-1]) def __nonzero__(self): return bool(self.proc) def _reqrep(self, msgid, *args, **kwargs): # convenience for YorickHandle hold = args[0] if hold and isinstance(hold, basestring) and hold[0]=='\05': hold = True else: hold = False reply = Message() self.proc.reqrep(Message(msgid, *args, **kwargs), reply) while (reply.packets and reply.packets[0][0] >= ID_EVAL and self.proc.pid is not None): if self.proc._debug: print("P>_reqrep: begin processing request (non-passive reply)") reply = reply.getreply(self.proc._debug, self._namespace) if not reply: raise PYorickError("yorick sent unknown active reply to request") if self.proc._debug: print("P>_reqrep: sending reply to request") self.proc.sendmsg(reply) reply = Message() # get the next reply from yorick self.proc.recvmsg(reply) if self.proc._debug: print("P>_reqrep: got passive reply to original request") if (self.proc.pid is None): return None; reply = reply.decode() if not isinstance(reply, tuple): if not hold: return reply if (isinstance(reply, np.ndarray) and reply.dtype==np.dtype(c_long) and reply.shape==()): return YorickHold(self, reply) if reply == (ID_EOL, (2,), {}): if msgid == ID_GETVAR: return YorickVarDerived(self, 0, args[0]) elif msgid in [ID_EVAL, ID_FUNCALL, ID_GETSLICE]: return YorickHold(self, self._reqrep(ID_GETVAR, '')) raise PYorickError("yorick sent error reply to request") def _server(self, namespace=None): print("--> yorick prompt (type py to return to python):") self.proc.interact(YorickServer(namespace)) print("--> python prompt:") class Key2Attr(object): """Base class to convert attributes to keys, s/getattr --> s/getitem.""" def __getattr__(self, name): # pipe.name """Convert get attribute to get item.""" # inspect module causes serious problems by probing for names # ipython also probes for getdoc attribute if (len(name)>3 and name[0:2]=='__' and name[-2:]=='__') or name=='getdoc': raise AttributeError("Key2Attr instance has no attribute '"+name+"'") if name not in self.__dict__: # unnecessary? never false? return self[name] else: return self.__dict__[name] def __setattr__(self, name, value): """Convert set attribute to set item.""" if name not in self.__dict__: self[name] = value else: object.__setattr__(self, name, value) # this is intended to wrap yorick file handles or oxy objects class Key2AttrWrapper(Key2Attr): """Wrap an arbitrary object so its attributes become its mapping keys.""" def __init__(self, obj): self.__dict__['_key2attr__'] = obj # eventually may want to retain more extensive set of obj methods def __repr__(self): s = "" return s.format(repr(self.__dict__['_key2attr__'])) def __nonzero__(self): return bool(self.__dict__['_key2attr__']) def __getitem__(self, key=None): return self.__dict__['_key2attr__'][key] def __setitem__(self, key, value): self.__dict__['_key2attr__'][key] = value def __call__(self, command=None, *args, **kwargs): return self.__dict__['_key2attr__'](*args, **kwargs) class YorickHandle(Key2Attr): """Object whose attributes are yorick variables. Do not attempt to probe with hasattribute or other introspection! """ # Every attribute in this class should represent a yorick variable. # The __XXX__ system names cannot be retrieved, nor can the # practically unavoidable _reftype__ and _yorick__ attributes. # However, no other attributes are permitted. # must avoid __setattr__, __getattr__ by explicit calls through __dict__ def __init__(self, reftype, bare): self.__dict__['_reftype__'] = reftype self.__dict__['_yorick__'] = bare def __repr__(self): bare = self.__dict__['_yorick__'] typ = ['call', 'evaluate', 'value'][self.__dict__['_reftype__']] s = "" return s.format(typ, repr(bare.proc)[1:-1]) def __nonzero__(self): return bool(self.__dict__['_yorick__']) def __getitem__(self, key=None): """Return parent connection, avoiding use of an attribute.""" bare = self.__dict__['_yorick__'] if not key: return Yorick(bare) typ = self.__dict__['_reftype__'] if typ == 2: return bare._reqrep(ID_GETVAR, key) return YorickVarDerived(bare, typ, key) def __setitem__(self, key, value): """Implement handle.name = value.""" bare = self.__dict__['_yorick__'] if key not in self.__dict__: bare._reqrep(ID_SETVAR, key, value) else: object.__setattr__(self, key, value) def __call__(self, command=None, *args, **kwargs): """Implement handle(command) or handle(format, args, key=kwds).""" if args or kwargs: command = command.format(*args, **kwargs) bare = self.__dict__['_yorick__'] typ = self.__dict__['_reftype__'] if command: if command[0] == '=': # leading = forces eval semantics command = command[1:] typ = 1 elif command[0] == '@': # hold return value command = '\05' + command[1:] typ = 1 if command is None: bare._server(bare._namespace) elif typ: rslt = bare._reqrep(ID_EVAL, command) if command[0] == '\05': return rslt return rslt else: return bare._reqrep(ID_EXEC, command) class YorickVar(object): """Reference to a yorick variable.""" def __init__(self, bare, reftype, name): if not isinstance(name, basestring): raise PYorickError("illegal yorick variable name") self.bare = bare self.reftype = bool(reftype) self.name = name self._info = None def __repr__(self): bare = self.bare typ = ['call', 'evaluate'][self.reftype] s = "" return s.format(self.name, typ, repr(bare.proc)[1:-1]) def __nonzero__(self): return bool(self.bare) def __call__(self, *args, **kwargs): """Implement handle.name(args, kwargs).""" if self.reftype: return self.bare._reqrep(ID_FUNCALL, self.name, *args, **kwargs) else: self.bare._reqrep(ID_SUBCALL, self.name, *args, **kwargs) def __getitem__(self, key): """Implement handle.name[key].""" key = self._fix_indexing(key) return self.bare._reqrep(ID_GETSLICE, self.name, *key) def __setitem__(self, key, value): """Implement handle.name[key] = value.""" key = self._fix_indexing(key) + (value,) return self.bare._reqrep(ID_SETSLICE, self.name, *key) def _fix_indexing(self, key, force=False): if not isinstance(key, tuple): key = (key,) # only single index provided if self.reftype and not force: return key # convert from python index semantics to yorick index semantics ndxs = [] for ndx in key[::-1]: # reverse index order if isinstance(ndx, slice): if ndx: i, j, s = ndx.start, ndx.stop, ndx.step if i is None: i = 0 i += 1 # python.x[i:etc] --> yorick.x(i+1:etc) if (s is not None) and s < 0: j += 2 # len=stop-step --> len=stop-step+1 # could also detect here? ndx = slice(i, j, s) elif isinstance(ndx, Number) or isinstance(ndx, np.ndarray): if isinstance(ndx, bool): ndx = int(ndx) ndx += 1 # python.x[i] --> yorick.x(i+1) elif isinstance(ndx, bytearray): ndx = np.frombuffer(ndx, dtype=np.uint8) + 1 elif isinstance(ndx, Sequence): shape, typ = codec.nested_test(ndx) if typ == Number: ndx = np.array(ndx) + 1 # python.x[i] --> yorick.x(i+1) ndxs.append(ndx) return tuple(ndxs) @property def info(self): """Implement handle.name.info.""" name = self.name if name[0] == '\05': name = name[1:] if self._info is None: self._info = tuple(self.bare._reqrep(ID_GETSHAPE, name)) return self._info @property def is_string(self): return self.info[0] == ID_STRING @property def is_number(self): return self.info[0] in range(0,15) @property def is_bytes(self): return self.info[0] == 8 @property def is_integer(self): return self.info[0] in [0,1,2,3,4,8,9,10,11,12] @property def is_real(self): return self.info[0] in [5, 6, 7] @property def is_complex(self): return self.info[0] in [13, 14, 15] @property def is_func(self): return self.info[0] == -1 @property def is_list(self): return self.info[0] == -2 @property def is_dict(self): return self.info[0] == -3 @property def is_range(self): return self.info[0] == -4 @property def is_nil(self): return self.info[0] == -5 @property def is_obj(self): return self.info[0] == -8 # oxy obj not list or dict @property def shape(self): if self.info[0] >= 0: return self._info[-1:1:-1] else: return None @property def is_file(self): if self.info[0] == -6: return 1 elif self._info[0] == -7: return 2 else: return 0 @property def value(self): """Implement handle.name.value.""" name = self.name if name[0] == '\05': name = name[1:] return self.bare._reqrep(ID_GETVAR, name) # single character alias for interactive use v = value @property def call(self): """Implement handle.name.call.""" if self.reftype: name = self.name if name[0] == '\05': name = name[1:] if name[0]>='9' or name[0]<='0': return YorickVarDerived(self.bare, False, name) else: return YorickVarCall(self, name, False) return self # single character alias for interactive use c = call @property def evaluate(self): """Implement handle.name.evaluate.""" if not self.reftype: if self.name[0]>='9' or self.name[0]<='0': return YorickVarDerived(self.bare, True, self.name) else: return YorickVarCall(self, self.name, True) return self # single character alias for interactive use e = evaluate @property def hold(self): """Implement handle.name.hold.""" if self.name[0] != '\05': if self.name[0]>='9' or self.name[0]<='0': return YorickVarDerived(self.bare, True, '\05'+self.name) else: return YorickVarCall(self, '\05'+self.name, True) return self # Hook for packages (like a lazy evaluator) to customize YorickVar; # YorickVarDerived is the object a YorickHandle uses. # The YorickVarDerived class must be a derived class of YorickVar. # The derived class must call YorickVar.__init__ in its constructor. YorickVarDerived = YorickVar class YorickHold(YorickVar): """Reference to a yorick anonymous result, holding use of result.""" def __init__(self, bare, n): if isinstance(n, np.ndarray): n = int(n) if (not isinstance(n, Number)) or n<=3: raise PYorickError("illegal yorick reference number") self.bare = bare self.reftype = True self.name = str(n) self._info = None def __del__(self): # free use of value in yorick if (self.bare): name = self.name if name[0] == '\05': name = name[1:] self.bare._reqrep(ID_EXEC, "_pyorick_refs,1,"+name) class YorickVarCall(object): """Reference to anonymous yorick variable callable only.""" def __init__(self, var, name, reftype): self.var = var # holds use of YorickHold object var self.name = name self.reftype = reftype def __call__(self, *args, **kwargs): """Implement handle.name(args, kwargs).""" if self.reftype: return self.var.bare._reqrep(ID_FUNCALL, self.name, *args, **kwargs) else: self.var.bare._reqrep(ID_SUBCALL, self.name, *args, **kwargs) def __getitem__(self, key): """Implement handle.name[key].""" if not self.reftype: key = self.var._fix_indexing(key, True) return self.var.bare._reqrep(ID_GETSLICE, self.name, *key) @property def call(self): """Implement handle.name.call.""" if self.reftype: name = self.name if name[0] == '\05': name = name[1:] return YorickVarCall(self.var, name, False) return self # single character alias for interactive use c = call @property def hold(self): """Implement handle.name.hold.""" if self.name[0] != '\05': return YorickVarCall(self.var, '\05'+self.name, True) return self class YorickServer(object): """Server to accept requests from and generate replies to yorick.""" def __init__(self, namespace, debug=False): self.namespace = namespace self.debug = debug def start(self, command=None): """Start server, optionally returning exec msg to be sent to yorick.""" self.started = False self.request = Message() # provide container for first request if command: # Unless this Process has some out-of-band way to enter terminal mode, # yorick will be expecting a request. Execing this yorick command # must cause yorick to begin emitting requests rather than replies. return Message(ID_EXEC, command) def reply(self, debug=False): """Return message to be sent in reply to self.request.""" if debug: print("P>server reply: decoding") rep = self.request.getreply(debug, self.namespace) self.request = Message() # empty container for next request if rep is False: if debug: print("P>server reply: got signal to exit terminal mode") return None # signal to exit terminal mode if isinstance(rep, Message): self.started = True return rep if not self.started: # assume yorick never entered terminal mode if debug: print("P>server reply: yorick never entered terminal mode") self.request = None return None return Message(ID_EOL, 1) # yorick needs error to continue # Provide two cleanup options: # 1. finish() or finish(command) to optionally send a final yorick command # - if command supplied, server.request and server.reply() one last time # 2. final(value) to send a final value back to yorick def finish(self, command=None): """Stopping server, optionally returning exec msg to be sent to yorick.""" if command: return Message(ID_EXEC, command) # Empty request message from start or reply already present. # Caller may call reply one final time if needed. def final(self, value): """Stopping server, returning data message to be sent to yorick.""" return Message(None, value) class Message(object): """Message to or from yorick in raw protocol-wire form. msg = Message(msgid, arglist) for active messages msg = Message(None, value) for data messages msg = Message() for an empty message, to call reader packetlist = msg.reader() return generator to receive from process value = msg.decode() return value of msg built by packetlist """ """ A message is a list of packets, where each packet is an ndarray. Messages must be sent and received atomically, which is why they are marshalled in a Message instance in the raw format, so that none of the encode or decode logic, which may raise formatting exceptions, is interspersed with the sending or receiving. Constructor: Encode active message, where msgid is ID_EVAL, ID_EXEC, etc., and the argument list depends on which message: msg = Message(ID_EVAL, 'yorick expression') msg = Message(ID_EXEC, 'yorick code') msg = Message(ID_GETVAR, 'varname') msg = Message(ID_SETVAR, 'varname', value) msg = Message(ID_FUN/SUBCALL, 'fname', arg1, arg2, ..., key1=k1, ...) msg = Message(ID_GETSLICE, 'aname', index1, index2, ...) msg = Message(ID_SETSLICE, 'aname', index1, index2, ..., value) msg = Message(ID_GETSHAPE, 'varname') Passive EOL end-of-list message: msg = Message(ID_EOL, flag) flag defaults to 0 Data messages ordinarily created using Message(None, value): msg = Message(ID_LST/DCT, list or dict) msg = Message(ID_NIL) msg = Message(ID_SLICE, flags, start, stop, step) msg = Message(ID_STRING, shape, lens, value) msg = Message(0 thru 15, shape, value) for numeric arrays The reader method returns a generator which can be used to build a message starting from an empty message: packetlist = msg.reader() for packet in packetlist: read raw ndarray into packet, which has required dtype and shape After this loop, msg.packets will contain the list of ndarrays. The decode method converts msg.packets into a value if the message is data. Otherwise (for active messages or EOL) it produces a tuple (msgid, args, kwargs) which could be passed to the Message constructor to recreate the message. value = msg.decode() if isinstance(value, tuple): this is an instruction (active message or ID_EOL) else: this is data """ def __init__(self, *args, **kwargs): self.packets = [] if not args: return None msgid = args[0] if msgid is None: msgid, args, kwargs = codec.encode_data(*args[1:]) else: args = args[1:] codec.idtable[msgid].encoder(self, msgid, *args, **kwargs) def reader(self): return codec.reader(self) def decode(self): if not self.packets: raise PYorickError("cannot decode empty message") self.pos = 1 # pos=0 already processed here return codec.idtable[self.packets[0][0]].decoder(self) def getreply(self, debug=False, namespace=None): """Return message to be sent in reply to this request.""" if debug: print("P>getreply: decoding") if namespace is None: namespace = server_namespace elif not isinstance(namespace, Mapping): namespace = namespace.__dict__ # decode presumed request message # returns: # Message reply, including EOL for syntax or # None if not a recognized request # False if signal to exit terminal mode req = self.decode() code = None if isinstance(req, tuple): if debug: print("P>getreply: req[0]="+str(req[0])) if req[0] in [ID_EXEC, ID_EVAL, ID_GETVAR, ID_SETVAR, ID_FUNCALL, ID_SUBCALL, ID_GETSLICE, ID_SETSLICE]: text = req[1][0].replace('\0', '\n') if req[0] == ID_SETVAR: namespace['_pyorick_setvar_rhs_'] = req[1][-1] text += '=_pyorick_setvar_rhs_' # note: if locals dict specified, must prepend "global varname;" try: if req[0] in [ID_EXEC, ID_SETVAR]: if not text: # alternate signal to exit terminal mode (if no start command) if debug: print("P>getreply: got exit terminal signal") return False code = compile(text, '', 'exec') else: code = compile(text, '', 'eval') if debug: print("P>getreply: compiled text="+text) except SyntaxError: if debug: print("P>getreply: syntax error, text="+text) return Message(ID_EOL, 1) # reply with error to yorick elif req[0]==ID_EOL and not req[1][0]: # this is signal to exit terminal mode (matches start command) if debug: print("P>getreply: got exit terminal signal") return False if code: try: # first, eval the text sent as command or variable name obj = eval(code, namespace) rslt = None if req[0] in [ID_EXEC, ID_EVAL, ID_GETVAR, ID_SETVAR]: rslt = obj if req[0] == ID_SETVAR: del namespace['_pyorick_setvar_rhs_'] elif req[0] in [ID_FUNCALL, ID_SUBCALL]: rslt = obj(*req[1][1:], **req[2]) if req[0] == ID_SUBCALL: rslt = None # discard any return value elif req[0] == ID_GETSLICE: rslt = obj[req[1][1:]] elif req[0] == ID_SETSLICE: obj[req[1][1:]] = req[1][-1] return Message(None, rslt) except: if debug: print("P>getreply: execution error") raise # any exceptions trying to eval or encode reply are yorick's problem pass return Message(ID_EOL, 1) # reply with error to yorick return None # Here is a pseudo-bnf description of the message grammar: # # message := narray numeric array # | sarray string array, nested list in python # | slice array index selecting a subset # | nil [] in yorick, None in python # | list list in python, anonymous oxy object in yorick # | dict dict in python, oxy object in yorick # | eol end-of-list, variants used for other purposes # | eval parse text and return expression value # | exec parse text and execute code, no return value # | getvar return variable value # | setvar set variable value # | funcall invoke function, returning value # | subcall invoke function as subroutine, no return value # | getslice return slice of array # | setslice set slice of array # | getshape return type and shape of array, but not value # narray := long[2]=(0..15, rank) shape data # sarray := long[2]=(16, rank) shape lens text # slice := long[2]=(17, flags) long[3]=(start, stop, step) # nil := long[2]=(18, 0) # list := long[2]=(19, 0) llist # dict := long[2]=(20, 0) dlist # eol := long[2]=(21, flags) # eval := long[2]=(32, textlen) text # exec := long[2]=(33, textlen) text # getvar := long[2]=(34, namelen) name # setvar := long[2]=(35, namelen) name value # funcall := long[2]=(36, namelen) name alist # subcall := long[2]=(37, namelen) name alist # getslice := long[2]=(38, namelen) name ilist # setslice := long[2]=(39, namelen) name llist value # getvar := long[2]=(40, namelen) name # # shape := long[rank] nothing if rank=0 # data := type[shape] # lens := long[shape] # text := char[textlen or sum(lens)] # llist := eol(0) # | value llist # dlist := eol(0) # | setvar llist # name := char[namelen] # value := narray | sarray | slice | nil | list | dict | getvar # alist := eol(0) # := value alist # := setvar alist # type numbers needed during execution of class codec definition # id 0-15 are numeric types: # char short int long longlong float double longdouble # followed by unsigned (integer) or complex (floating) variants # numeric protocol datatypes are C-types (byte is C char) id_types = [c_byte, c_short, c_int, c_long, c_longlong, c_float, c_double, c_longdouble, c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong, np.csingle, np.complex_, None] # no portable complex long double # other passive messages (reply prohibited): ID_STRING, ID_SLICE, ID_NIL, ID_LST, ID_DCT, ID_EOL =\ 16, 17, 18, 19, 20, 21 # ID_STRING: yorick assumes iso_8859_1, need separate id for utf-8? # active messages (passive reply required): ID_EVAL, ID_EXEC, ID_GETVAR, ID_SETVAR, ID_FUNCALL, ID_SUBCALL =\ 32, 33, 34, 35, 36, 37 ID_GETSLICE, ID_SETSLICE, ID_GETSHAPE =\ 38, 39, 40 # convenience values ID_LONG = 3 ID_NUMERIC = [i for i in range(16)] # Each instance of Clause represents a clause of the message grammar. # At minimum, the functions to build, encode, and decode that clause must # be defined. These definitions are in codec below. # Clause primarily implements the decorators used to cleanly construct # codec. class Clause(object): def __init__(self, idtable=None, *idlist): self.idlist = idlist # tuple of message ids if top level clause for msgid in idlist: idtable[msgid] = self # The reader, encoder, and decoder are decorator functions for codec, # which shadow themselves in each instance. # Note that the shadow version is an ordinary function, not a method, # implicitly @staticmethod. # (Inspired by property setter and deleter decorators.) def reader(self): def add(func): self.reader = func return self return add def encoder(self): def add(func): self.encoder = func return self return add def decoder(self): def add(func): self.decoder = func return self return add # These were originally members of the codec class, but that breaks in # python 3. # See http://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition typesz = [np.dtype(id_types[i]).itemsize for i in range(15)] + [0] typesk = ['i']*5 + ['f']*3 + ['u']*5 + ['c']*2 + ['none'] typesk = [typesk[i]+str(typesz[i]) for i in range(16)] # keys for id_typtab # lookup table for msgid given typesk (computable from dtype) id_typtab = [0, 1, 2, 4, 3, 5, 7, 6, 8, 9, 10, 12, 11, 13, 15, 14] id_typtab = dict([[typesk[id_typtab[i]], id_typtab[i]] for i in range(16)]) del typesz, typesk # prefix is 'thisispickled_'+md5sum('thisispickled\n') ypickling_prefix = bytearray(b'thisispickled_8ad5f009982d6a1bcb5d3de476751a79') ypickling_nprefix = len(ypickling_prefix) class codec(object): # not really a class, just a convenient container """Functions and tables to build, encode, and decode messages.""" # This collection of methods makes protocol flexible and extensible. # To add new message type(s): # 1. Choose a new msgid number(s), and a name for the top level clause. # 2. name = Clause(msgid [, ident2, ident3, ...]) # 3. Write the reader, encoder, and decoder methods (see below). # Note that the reader method is a generator function; the others # are ordinary functions. The first argument is always msg, the current # message, which you may use as you like to store state information. # The packets attribute of msg is the list of packets; each packet must # be an ndarray. # dict of top level clauses by key=message id idtable = {} # idtable[msgid] --> top level message handler for msgid enpickle = depickle = True # pickling is on by default @staticmethod def reader(msg): if msg.packets: raise PYorickError("attempt to read into non-empty message") packet = nplongs(0, 0) msg.packets.append(packet) yield packet for packet in codec.idtable[packet[0]].reader(msg): yield packet narray = Clause(idtable, *ID_NUMERIC) @narray.reader() def narray(msg): msgid, rank = msg.packets[-1] shape = np.zeros(rank, dtype=c_long) if rank > 0: msg.packets.append(shape) yield shape msg.packets.append(np.zeros(shape[::-1], dtype=id_types[msgid])) yield msg.packets[-1] @narray.encoder() def narray(msg, msgid, shape, value): rank = len(shape) msg.packets.append(nplongs(msgid, rank)) if rank: msg.packets.append(nplongs(*shape[::-1])) msg.packets.append(value) @narray.decoder() def narray(msg): pos = msg.pos ischar = (msg.packets[pos-1][0] in [0,8]) rank = msg.packets[pos-1][1] if rank: msg.pos = pos = pos+1 msg.pos += 1 if ischar and rank==1 and codec.depickle: return codec.pickleloads(msg.packets[pos]) return msg.packets[pos] sarray = Clause(idtable, ID_STRING) @sarray.reader() def sarray(msg): msgid, rank = msg.packets[-1] shape = np.zeros(rank, dtype=c_long) if rank > 0: msg.packets.append(shape) yield shape lens = np.zeros(shape[::-1], dtype=c_long) msg.packets.append(lens) yield lens lens = lens.sum() if lens: msg.packets.append(np.zeros(lens, dtype=np.uint8)) yield msg.packets[-1] @sarray.encoder() def sarray(msg, msgid, shape, lens, value): codec.narray.encoder(msg, ID_LONG, shape, lens) if len(shape): msg.packets[-3][0] = ID_STRING else: msg.packets[-2][0] = ID_STRING if value.nbytes: msg.packets.append(value) @sarray.decoder() def sarray(msg): pos = msg.pos rank = msg.packets[pos-1][1] if rank: msg.pos = pos = pos+1 msg.pos += 1 lens = msg.packets[pos] if lens.sum(): pos = msg.pos msg.pos += 1 value = msg.packets[pos] else: value = np.zeros(0, dtype=np.uint8) return codec.decode_sarray(lens, value) # as nested list slice = Clause(idtable, ID_SLICE) @slice.reader() def slice(msg): msg.packets.append(nplongs(0, 0, 0)) yield msg.packets[-1] @slice.encoder() def slice(msg, msgid, x, flags=None): if not flags: if x.start is None: smin, flags = 0, 1 else: smin, flags = x.start, 0 if x.stop is None: smax, flags = 0, flags+2 else: smax = x.stop if x.step is None: sinc = (-1, 1)[bool(flags) or smin<=smax] else: sinc = x.step else: smin = smax = 0 sinc = 1 msg.packets.append(nplongs(msgid, flags)) msg.packets.append(nplongs(smin, smax, sinc)) @slice.decoder() def slice(msg): pos = msg.pos flags = msg.packets[pos-1][1] if flags == 7: value = ynewaxis # np.newaxis confused with nil elif flags == 11: value = Ellipsis else: value = msg.packets[pos].tolist() if flags&1: value[0] = None if flags&2: value[1] = None value = slice(*value) msg.pos += 1 return value nil = Clause(idtable, ID_NIL) @nil.reader() def nil(msg): return yield # this is a generator that raises StopIteration on first call @nil.encoder() def nil(msg, msgid): msg.packets.append(nplongs(msgid, 0)) @nil.decoder() def nil(msg): return None lst = Clause(idtable, ID_LST) @lst.reader() def lst(msg): for packet in codec.qmlist.reader(msg, 0): yield packet @lst.encoder() def lst(msg, msgid, value): msg.packets.append(nplongs(msgid, 0)) codec.qmlist.encoder(msg, 0, value, {}) @lst.decoder() def lst(msg): value = [] codec.qmlist.decoder(msg, 0, value, {}) return value dct = Clause(idtable, ID_DCT) @dct.reader() def dct(msg): for packet in codec.qmlist.reader(msg, 1): yield packet @dct.encoder() def dct(msg, msgid, value): msg.packets.append(nplongs(msgid, 0)) codec.qmlist.encoder(msg, 1, (), value) @dct.decoder() def dct(msg): value = {} codec.qmlist.decoder(msg, 1, None, value) return value eol = Clause(idtable, ID_EOL) @eol.reader() def eol(msg): return yield # this is a generator that raises StopIteration on first call @eol.encoder() def eol(msg, msgid, flag=0): msg.packets.append(nplongs(ID_EOL, flag)) @eol.decoder() def eol(msg): return (ID_EOL, (int(msg.packets[msg.pos-1][1]),), {}) evaluate = Clause(idtable, ID_EVAL, ID_EXEC) @evaluate.reader() def evaluate(msg): packet = np.zeros(msg.packets[-1][1], dtype=np.uint8) if packet.nbytes: msg.packets.append(packet) yield packet @evaluate.encoder() def evaluate(msg, msgid, text): text = np.fromiter(bytearray(text.encode('iso_8859_1')), dtype=np.uint8) msg.packets.append(nplongs(msgid, len(text))) if len(text): msg.packets.append(text) @evaluate.decoder() def evaluate(msg): pos = msg.pos if msg.packets[pos-1][1]: msg.pos += 1 text = codec.array2string(msg.packets[pos]) else: text = '' return (msg.packets[pos-1][0], (text,), {}) # same as evaluate, but may want to add name sanity checks someday getvar = Clause(idtable, ID_GETVAR, ID_GETSHAPE) @getvar.reader() def getvar(msg): packet = np.zeros(msg.packets[-1][1], dtype=np.uint8) if packet.nbytes: msg.packets.append(packet) yield packet @getvar.encoder() def getvar(msg, msgid, name): name = np.fromiter(bytearray(name.encode('iso_8859_1')), dtype=np.uint8) msg.packets.append(nplongs(msgid, len(name))) if len(name): msg.packets.append(name) @getvar.decoder() def getvar(msg): pos = msg.pos if msg.packets[pos-1][1]: msg.pos += 1 name = codec.array2string(msg.packets[pos]) else: name = '' return (msg.packets[pos-1][0], (name,), {}) setvar = Clause(idtable, ID_SETVAR) @setvar.reader() def setvar(msg): packet = np.zeros(msg.packets[-1][1], dtype=np.uint8) if packet.nbytes: msg.packets.append(packet) yield packet packet = nplongs(0, 0) msg.packets.append(packet) yield packet msgid = msg.packets[-1][0] if msgid not in codec.qmlist.allowed[0]: raise PYorickError("illegal setvar value msgid in reader") for packet in codec.idtable[msgid].reader(msg): yield packet @setvar.encoder() def setvar(msg, msgid, name, value): name = np.fromiter(bytearray(name.encode('iso_8859_1')), dtype=np.uint8) msg.packets.append(nplongs(msgid, len(name))) if len(name): msg.packets.append(name) msgid, args, kwargs = codec.encode_data(value) if msgid not in codec.qmlist.allowed[0]: raise PYorickError("illegal setvar value msgid in encoder") codec.idtable[msgid].encoder(msg, msgid, *args, **kwargs) @setvar.decoder() def setvar(msg): pos = msg.pos if msg.packets[pos-1][1]: name = codec.array2string(msg.packets[pos]) pos += 1 else: name = '' msg.pos = pos + 1 args = (name, codec.idtable[msg.packets[pos][0]].decoder(msg)) return (ID_SETVAR, args, {}) funcall = Clause(idtable, ID_FUNCALL, ID_SUBCALL) @funcall.reader() def funcall(msg): packet = np.zeros(msg.packets[-1][1], dtype=np.uint8) if packet.nbytes: msg.packets.append(packet) yield packet for packet in codec.qmlist.reader(msg, 2): yield packet @funcall.encoder() def funcall(msg, msgid, name, *args, **kwargs): codec.getvar.encoder(msg, msgid, name) codec.qmlist.encoder(msg, 2, args, kwargs) @funcall.decoder() def funcall(msg): pos = msg.pos if msg.packets[pos-1][1]: msg.pos += 1 name = codec.array2string(msg.packets[pos]) else: name = '' args = [] kwargs = {} codec.qmlist.decoder(msg, 2, args, kwargs) return (msg.packets[pos-1][0], (name,)+tuple(args), kwargs) getslice = Clause(idtable, ID_GETSLICE) @getslice.reader() def getslice(msg): packet = np.zeros(msg.packets[-1][1], dtype=np.uint8) if packet.nbytes: msg.packets.append(packet) yield packet for packet in codec.qmlist.reader(msg, 0): yield packet @getslice.encoder() def getslice(msg, msgid, name, *args): codec.getvar.encoder(msg, msgid, name) codec.qmlist.encoder(msg, 0, args, {}) @getslice.decoder() def getslice(msg): pos = msg.pos if msg.packets[pos-1][1]: msg.pos += 1 name = codec.array2string(msg.packets[pos]) else: name = '' args = [] codec.qmlist.decoder(msg, 0, args, {}) return (msg.packets[pos-1][0], (name,)+tuple(args), {}) setslice = Clause(idtable, ID_SETSLICE) @setslice.reader() def setslice(msg): packet = np.zeros(msg.packets[-1][1], dtype=np.uint8) if packet.nbytes: msg.packets.append(packet) yield packet for packet in codec.qmlist.reader(msg, 0): yield packet packet = nplongs(0, 0) msg.packets.append(packet) yield packet msgid = msg.packets[-1][0] if msgid not in codec.qmlist.allowed[0]: raise PYorickError("illegal setslice value msgid in reader") for packet in codec.idtable[msgid].reader(msg): yield packet @setslice.encoder() def setslice(msg, msgid, name, *args): codec.getvar.encoder(msg, msgid, name) if len(args) < 1: raise PYorickError("missing setvar value msgid in encoder") codec.qmlist.encoder(msg, 0, args[0:-1], {}) msgid, args, kwargs = codec.encode_data(args[-1]) if msgid not in codec.qmlist.allowed[0]: raise PYorickError("illegal setvar value msgid in encoder") codec.idtable[msgid].encoder(msg, msgid, *args, **kwargs) @setslice.decoder() def setslice(msg): pos = msg.pos if msg.packets[pos-1][1]: msg.pos += 1 name = codec.array2string(msg.packets[pos]) else: name = '' args = [] codec.qmlist.decoder(msg, 0, args, {}) pos = msg.pos msg.pos += 1 value = codec.idtable[msg.packets[pos][0]].decoder(msg) return (ID_SETSLICE, (name,)+tuple(args)+(value,), {}) # eol terminated lists, qmlist means "quoted message list" qmlist = Clause() @qmlist.reader() def qmlist(msg, kind): allowed = codec.qmlist.allowed[kind] while True: packet = nplongs(0, 0) msg.packets.append(packet) yield packet msgid = msg.packets[-1][0] if msgid not in allowed: if msgid!=ID_EOL or msg.packets[-1][1]: raise PYorickError("illegal list element msgid") break for packet in codec.idtable[msgid].reader(msg): yield packet @qmlist.encoder() def qmlist(msg, kind, args, kwargs): allowed = codec.qmlist.allowed[kind] for arg in args: msgid, iargs, ikwargs = codec.encode_data(arg) codec.idtable[msgid].encoder(msg, msgid, *iargs, **ikwargs) for key in kwargs: codec.setvar.encoder(msg, ID_SETVAR, key, kwargs[key]) codec.eol.encoder(msg, ID_EOL) @qmlist.decoder() def qmlist(msg, kind, args, kwargs): allowed = codec.qmlist.allowed[kind] while True: pos = msg.pos msg.pos += 1 packet = msg.packets[pos] msgid = packet[0] if msgid not in allowed: if msgid!=ID_EOL or packet[1]: # always caught by reader or encoder? raise PYorickError("illegal list element msgid (BUG?)") break item = codec.idtable[msgid].decoder(msg) if msgid == ID_SETVAR: kwargs[item[1][0]] = item[1][1] # dict[name] = value else: args.append(item) # set allowed msgids for the various types of list (used by reader) qmlist.allowed = [i for i in range(ID_EOL)] + [ID_GETVAR] qmlist.allowed = [qmlist.allowed, # llist [ID_SETVAR], # dlist qmlist.allowed+[ID_SETVAR]] # alist @staticmethod def array2string(a): s = a.tostring().decode('iso_8859_1') if s.endswith('\x00'): s = s[0:-1] return s @staticmethod def decode_sarray(lens, value): shape = lens.shape if shape: n = np.prod(shape) shape = shape[::-1] else: n = 1 # split value into 1D list of strings v lens = np.ravel(lens) i1 = np.cumsum(lens) i0 = i1 - lens i1 -= 1 v = [] for i in xrange(n): if lens[i]: v.append(codec.array2string(value[i0[i]:i1[i]])) else: v.append(ystring0) # reorganize v into nested lists for multidimensional arrays ndim = len(shape) for i in range(ndim-1): m = shape[i] v = [v[j:j+m] for j in xrange(0, n, m)] n /= m # handle scalar if not ndim: v = v[0] return v @staticmethod def encode_sarray(shape, value): # flatten the nested list n = len(shape) if n: while n > 1: n -= 1 v = [] for item in value: v.extend(item) value = v else: value = [value] val = [] lens = [] for v in value: if '\0' in v: v = v[0:v.index('\0')+1] # truncate after first NULL elif not isinstance(v, YString0): v += '\0' v = v.encode('iso_8859_1') lens.append(len(v)) val.append(v) lens = np.array(lens, dtype=c_long).reshape(shape) val = np.array(bytearray(b''.join(val)), dtype=np.uint8) return (ID_STRING, (shape, lens, val), {}) # decode work done, but encode still needs to recogize python data @staticmethod def encode_data(value, dryrun=False): # return (msgid, args, kwargs) msgid = -1 # unknown initially if isinstance(value, Number): if dryrun: return True value = np.array(value) elif isinstance(value, bytearray): if dryrun: return True value = np.frombuffer(value, dtype=np.uint8) elif isinstance(value, basestring): if dryrun: return True return codec.encode_sarray((), value) elif isinstance(value, Sequence): # check for array-like nested sequence shape, typ = codec.nested_test(value) if typ == basestring: if dryrun: return True return codec.encode_sarray(shape, value) elif typ != Number: if dryrun: for v in value: if not codec.encode_data(v, True): return False return True # may raise errors later, but not array-like return (ID_LST, (value,), {}) if dryrun: return True # np.array converts nested list of numbers to ndarray value = np.array(value) # numeric arrays are the "money message" if isinstance(value, np.ndarray): shape = value.shape k = str(value.dtype.kind) if k in 'SUa': if dryrun: return True return codec.encode_sarray(shape, value.tolist()) if k not in 'biufc': if dryrun: return False if codec.enpickle: return codec.pickledumps(value) raise PYorickError("cannot encode unsupported array item type") if k == 'b': k = 'u' k += str(value.dtype.itemsize) if k not in id_typtab: if dryrun: return False if codec.enpickle: return codec.pickledumps(value) raise PYorickError("cannot encode unsupported array numeric dtype") if dryrun: return True msgid = id_typtab[k] if not value.flags['CARRAY']: value = np.copy(value, 'C') return (msgid, (shape, value), {}) # index range, including (newaxis, Ellipsis) <--> (-, ..) elif isinstance(value, NewAxis): # np.newaxis is unfortunately None if dryrun: return True return (ID_SLICE, (None, 7), {}) elif value is Ellipsis: if dryrun: return True return (ID_SLICE, (None, 11), {}) elif isinstance(value, slice): if dryrun: return True return (ID_SLICE, (value,), {}) elif value is None: if dryrun: return True return (ID_NIL, (), {}) # dict objects only allowed if all keys are strings elif isinstance(value, Mapping): if not all(isinstance(key, basestring) for key in value): if dryrun: return False if codec.enpickle: return codec.pickledumps(value) raise PYorickError("cannot encode dict with non-string key") if dryrun: for key in value: if not codec.encode_data(value[key], True): return False return True return (ID_DCT, (value,), {}) elif isinstance(value, YorickVar): if dryrun: return True return (ID_GETVAR, (value.name,), {}) else: if dryrun: return False if codec.enpickle: return codec.pickledumps(value) raise PYorickError("cannot encode unsupported data object") @staticmethod def nested_test(value): # value is a Sequence shape = (len(value),) if shape[0]: v = value[0] if isinstance(v, Number): if all(isinstance(v, Number) for v in value[1:]): return shape, Number elif isinstance(v, basestring): if all(isinstance(v, basestring) for v in value[1:]): return shape, basestring elif isinstance(v, Sequence): n, typ = codec.nested_test(v) if typ: for v in value[1:]: if isinstance(v, Sequence): m, t = codec.nested_test(v) if m==n and t==typ: continue return shape, None return shape + n, typ return shape, None @staticmethod def pickledumps(obj): v = np.frombuffer(ypickling_prefix + bytearray(pickle.dumps(obj, 2)), dtype=np.uint8) return (8, (v.shape, v), {}) @staticmethod def pickleloads(chars): if ypickling_prefix == bytearray(chars[0:ypickling_nprefix]): return pickle.loads(chars[ypickling_nprefix:].tostring()) return chars def nplongs(*args): return np.array(args, dtype=c_long) ######################################################################## def find_package_data(name): """See https://wiki.python.org/moin/Distutils/Tutorial""" # Idea: # The yorick startup script pyorick.i0 is a sibling of pyorick.py, # so that pyorick.i0 is found relative to __file__. # The setup.py packaging script can install pyorick.i0 in this way # by declaring it in package_data. However, this strategy may # fail for python platforms where packages are placed in zip files # or other non-filesystem places, see PEP 302 and pkgutil.get_data(). # The name pyorick.i0 (with a trailing 0) is necessary to prevent # distutils from recognizing the ".i" extension and treating the # file specially. Note that there may be portability issues relating # to the newline character. # This convention makes it straightforward to install pyorick "by hand" # when distutils cannot be used. # When pyorick.i0 is not found, check for it in the yorick user directory # ~/.yorick/ (or similar). If not found there, but pkgutil.get_data finds # it, unpack pyorick.i0 to ~/.yorick/ (or an existing yorick customization # directory). path = None try: p = __file__ if os.path.islink(p): p = os.path.realpath(p) p = os.path.join(os.path.dirname(os.path.abspath(p)), name) if os.path.isfile(p): path = p else: # before giving up, try ~/yorick directories home = os.path.expanduser('~') d = yuser = '.yorick' # first choice is ~/.yorick for d in [yuser, 'yorick', 'Library/Yorick', 'Application Data/Yorick', 'Yorick']: # possibilities, in order, checked in yorick/std0.c p = os.path.join(home, d) if os.path.isdir(p): yuser = p break p = os.path.join(yuser, name) if not os.path.isfile(p): path = p else: # last ditch effort, needed if pyorick loaded from a zip file import pkgutil d = pkgutil.get_data('pyorick', 'pyorick.i0') if d: d = d.decode('utf-8').splitlines() # removes universal newlines if not os.path.isdir(yuser): os.mkdir(yuser) with open(p, 'w') as f: for line in d: f.write("{0}\n".format(line)) path = p except: pass if path is None: raise PYorickError('unable to find '+name) return os.path.normcase(path) ypathd = "yorick" # default yorick command ipathd = find_package_data("pyorick.i0") # default pyorick.i0 include file class Process(object): def kill(self, dead=False): raise NotImplementedError("This process does not implement kill.") def reqrep(self, request, reply): raise NotImplementedError("This process does not implement reqrep.") def interact(self, server): raise NotImplementedError("This process does not implement interact.") def debug(self, on): raise NotImplementedError("This process does not implement debug.") class PipeProcess(Process): """Process using subprocess, binary pipes, and stdin/out/err pipes.""" def __init__(self, extra, ypath=None, ipath=None): if ypath is None: ypath = ypathd if ipath is None: ipath = ipathd self._debug = False argv = [ypath, '-q', '-i', ipath] # complete argv will be: argv rfd wfd extra ptoy = self.inheritable_pipe(0) ytop = self.inheritable_pipe(1) argv.extend([str(ptoy[0]), str(ytop[1])]) if extra: argv.extend(shlex.split(extra)) self.proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=False) # also consider: # universal_newlines=True # preexec_fn=function(closure?) of no arguments to close ptoy[1], ytop[0] # (unix only), see functools.partial # creationflags=CREATE_NEW_PROCESS_GROUP to be able to send CTRL_C_EVENT # (windows only) os.close(ptoy[0]) os.close(ytop[1]) self.rfd = ytop[0] self.wfd = ptoy[1] self.pid = self.proc.pid self.pfdw = self.proc.stdin.fileno() self.pfd = self.proc.stdout.fileno() self.killing = False # put yorick into interactive mode (no batch mode support) reply = Message() self.reqrep(Message(ID_EXEC, "pyorick, 1;"), reply, True) def __del__(self): self.kill() def __nonzero__(self): return self.pid is not None def kill(self, dead=False): if self.proc is not None and not self.killing: self.killing = True try: if not dead: self.send0("\nquit;") time.sleep(0.001) self.echo_pty() self.proc.stdin.close() # EOF on stdin also causes yorick to quit i = 0 while self.proc.poll() is None: time.sleep(0.001) i += 1 if i > 4: self.proc.kill() break finally: try: os.close(self.rfd) os.close(self.wfd) finally: self.kill(True) self.proc = None self.pid = self.pfdw = self.pfd = self.rfd = self.wfd = None self._debug = False def debug(self, on=None): if on is None: on = not self._debug if on != self._debug: # turn on/off pydebug flag in yorick reply = Message() self.reqrep(Message(ID_SETVAR, "pydebug", int(on)), reply) self._debug = on def sendmsg(self, request): try: # send request for packet in request.packets: self.send(packet) except: self.kill() raise PYorickError("failed to send complete message, yorick killed") def recvmsg(self, reply): prompt = None try: # receive reply for packet in reply.reader(): while True: # do not block on rfd when pfd pending p = select.select([self.pfd, self.rfd], [], [self.pfd, self.rfd]) if self.rfd in p[0]: break prompt = self.echo_pty() if prompt == 'PYORICK-QUIT> ': return # yorick has quit, and process killed by echo_pty self.recv(packet) except: self.kill() raise PYorickError("failed to receive complete message, yorick killed") if prompt == 'PYORICK-QUIT> ': return # yorick has quit, and process killed by echo_pty if self._debug: print("P>reqrep: reply="+str(reply.packets[0])) if reply.packets[0][0]==ID_EOL and reply.packets[0][1]==-1: self.kill(True) reply.packets[0][0] = ID_NIL elif (not prompt) and reply.packets[0][0]reqrep: request="+str(request.packets[0])) self.sendmsg(request) if self._debug: print("P>reqrep: blocking for reply...") self.recvmsg(reply) def interact(self, server): if self.pid is None: raise PYorickError("no yorick process running") self.echo_pty() # flush out any pending output server.start() if self._debug: print("P>interact: telling yorick to enter terminal mode") self.send0("pyorick, -1;") # tell yorick to enter terminal mode # handshake for yorick never entering terminal mode below prompt = None while True: # either prompt will arrive or another request try: p = select.select([self.pfd, self.rfd], [], [self.pfd, self.rfd]) if p[2]: self.kill() raise PYorickError("Select reports error, yorick killed.") if self.rfd in p[0]: for packet in server.request.reader(): self.recv(packet) rep = server.reply(self._debug) if self._debug: print("P>interact: reply ready to send? "+str(bool(rep))) if rep: for packet in rep.packets: self.send(packet) # yorick is blocked waiting for this else: break elif self.pfd in p[0]: # only get here when no more requests on rfd prompt = self.echo_pty() if prompt: # pass along prompt and wait for user to respond if prompt == 'PYORICK-QUIT> ': return self.send0(raw_input(prompt)) except KeyboardInterrupt: self.send0('\x03', True) # send ctrl-c to pty if server.request: # if not, never entered terminal mode self.echo_pty() # flush pending output before releasing yorick for packet in server.final(None).packets: self.send(packet) # handshake to exit terminal mode self.wait_for_prompt() def wait_for_prompt(self): if self._debug: print("P>wait_for_prompt: blocking...") while True: p = select.select([self.pfd], [], [self.pfd]) prompt = self.echo_pty() if prompt: return prompt def echo_pty(self): """Print yorick stdout/stderr, returning final prompt if any.""" if self.pfd is None: return None s = '' i = 0 # curiously hard to get reply promptly? while i < 3: # continue until no output pending try: p = select.select([self.pfd], [], [self.pfd], 0) except: p = ([], [], [self.pfd]) if p[0]: try: s += os.read(self.pfd, 16384).decode('iso_8859_1') except: p = (0, 0, 1) if p[2]: if not self.killing: self.kill() raise PYorickError("Read or select error on pty, yorick killed.") else: break if not p[0]: i += 1 prompt = None if s: # remove prompt in interactive (no idler) mode if s.endswith("> "): i = s.rfind('\n') + 1 # 0 on failure prompt = s[i:] s = s[0:i] if s: print(s, end='') # terminal newline already in s if prompt: if self._debug: print("P>echo_pty: prompt="+prompt) if prompt == 'PYORICK-QUIT> ' and not self.killing: self.kill(True) return prompt def send0(self, text, nolf=False): if self.pfd is not None: if not nolf: if not text.endswith('\n'): text += '\n' if self._debug and len(text): print("P>send0: nolf={0} text={1}".format(nolf, text)) n = 0 while n < len(text): try: n += os.write(self.pfdw, text[n:].encode('iso_8859_1')) except UnicodeEncodeError: print("<--- did not send non-ISO-8859-1 text to yorick --->") text = '\n' n = 0 except: self.kill(True) raise PYorickError("Unable to write to yorick stdin, yorick killed.") # See PEP 433. After about Python 3.3, pipes are close-on-exec by default. @staticmethod def inheritable_pipe(side): """Return a pipe that is *not* close-on-exec.""" p = os.pipe() if hasattr(fcntl, 'F_SETFD') and hasattr(fcntl, 'FD_CLOEXEC'): flags = fcntl.fcntl(p[side], fcntl.F_GETFD) flags &= ~fcntl.FD_CLOEXEC fcntl.fcntl(p[side], fcntl.F_SETFD, flags) return p def recv(self, packet): """Read numpy array packet from self.rfd.""" # other interfaces are readinto, copyto, frombuffer, getbuffer if self.rfd is None: return None # some fatal exception has already occurred # note: packet.data[n:] fails in python 3.4 if packet is scalar xx = packet.reshape(packet.size).view(dtype=np.uint8) n = 0 while n < packet.nbytes: try: s = os.read(self.rfd, packet.nbytes-n) # no way to use readinto? except: self.kill() # failure fatal, need to shut down yorick raise PYorickError("os.read failed, yorick killed") m = len(s) xx.data[n:n+m] = s # fails in python 3.4 unless xx dtype=np.unit8 n += m if self._debug and n: print("P>recv: {0} bytes".format(n)) def send(self, packet): """Write numpy array packet to self.wfd.""" if self.wfd is None: return None # some fatal exception has already occurred # note: packet.data[n:] fails in python 3.4 if packet is scalar pp = packet.reshape(packet.size).view(dtype=np.uint8) n = 0 while n < packet.nbytes: try: m = os.write(self.wfd, pp.data[n:]) except: m = -1 if m<0: self.kill() # failure fatal, need to shut down yorick raise PYorickError("os.write failed, yorick killed") n += m if self._debug and n: print("P>send: {0} bytes sent".format(n)) ProcessDefault = PipeProcess ######################################################################## ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1675877106.0 pyorick-1.5/pyorick/test_pyorick.py0000664000175000017500000004050700000000000017501 0ustar00davedave00000000000000import unittest import numpy as np from pyorick import * # pyorick exposes only intended APIs # non-APIs which must be exposed for testing from pyorick import Message, YorickVar, YorickHold, YorickVarCall from pyorick import (ID_EOL, ID_EVAL, ID_EXEC, ID_GETVAR, ID_SETVAR, ID_FUNCALL, ID_SUBCALL, ID_GETSLICE, ID_SETSLICE, ID_GETSHAPE) import __main__ # nosetests --with-coverage --cover-package=pyorick class ExampleClass(object): def __init__(self, thing): self.thing = thing def __eq__(self, other): return self.thing == other.thing def example_func(x): return x # create test fixtures def setup_data(self): # various types of scalar objects which must be encodable self.scalars = [65, 6.5, 0.+6.5j, True, bytearray(b'B'), np.array(65, dtype=np.short), np.array(65, dtype=np.intc), np.array(6.5, dtype=np.single), 'test string', '', ystring0, slice(1,5,2), Ellipsis, ynewaxis, None] # various types of array objects which must be encodable self.arrays = [s+np.zeros((3,2), dtype=s.__class__) for s in self.scalars[0:4]] self.arrays.append(np.array([[66,66],[66,66],[66,66]], dtype=np.uint8)) self.arrays.extend([s+np.zeros((3,2), dtype=s.dtype) for s in self.scalars[5:8]]) self.arrays.append([[66,66],[66,66],[66,66]]) self.arrays.append(bytearray(b'BABABABA')) # various types of string array objects which must be encodable self.strings = [['', 'test 1', 'another string'], [['', 'test 1', 'another string'], ['test 2', ystring0, 'more']]] self.strings.append(np.array(self.strings[1])) # corrupts string0? # representable list and dict objects self.groups = [(), [], ([], None), self.scalars, {}, {'key'+str(k):self.scalars[k] for k in range(len(self.scalars))}, [[1,'abc'], {'a':1, 'b':[2,'c',4]}], {'key0':[1,'abc'], 'key1':{'a':1, 'b':2}}] # unrepresentable objects self.bad = [{'a':[1,2,3], 2:[4,5,6]}, # illegal key type example_func, # function ExampleClass, # class ExampleClass([1,2,3])] # class instance class TestCodec(unittest.TestCase): def setUp(self): setup_data(self) def tearDown(self): pass def test_scalars(self): """Check that scalar types can be encoded and decoded.""" for i in range(len(self.scalars)): s = self.scalars[i] self.assertTrue(yencodable(s), 'yencodable fails item '+str(i)) msg = Message(None, s) v = msg.decode() self.assertEqual(s, v, 'codec failed on item '+str(i)) def test_arrays(self): """Check that array types can be encoded and decoded.""" for i in range(len(self.arrays)): s = self.arrays[i] self.assertTrue(yencodable(s), 'yencodable fails item '+str(i)) msg = Message(None, s) v = msg.decode() self.assertTrue(np.array_equal(np.array(s), v), 'codec failed on item '+str(i)) def test_strings(self): """Check that string types can be encoded and decoded.""" for i in range(len(self.strings)): s = self.strings[i] self.assertTrue(yencodable(s), 'yencodable fails item '+str(i)) msg = Message(None, s) v = msg.decode() if isinstance(s, np.ndarray): s = s.tolist() self.assertEqual(s, v, 'codec failed on item '+str(i)) def test_groups(self): """Check that group types can be encoded and decoded.""" for i in range(len(self.groups)): s = self.groups[i] self.assertTrue(yencodable(s), 'yencodable fails item '+str(i)) msg = Message(None, s) v = msg.decode() if isinstance(s, tuple): s = list(s) self.assertEqual(s, v, 'codec failed on item '+str(i)) def test_bad(self): """Check that unencodable types cannot be encoded.""" for i in range(len(self.bad)): s = self.bad[i] self.assertFalse(yencodable(s), 'yencodable fails item '+str(i)) ypickling(False) with self.assertRaises(PYorickError) as cm: msg = Message(None, s) self.assertIsInstance(cm.exception, PYorickError, 'codec failed on item '+str(i)) ypickling(encode=True, decode=True) print('doing {}'.format(i)) msg = Message(None, s) v = msg.decode() self.assertEqual(s, v, 'codec failed on item '+str(i)) def test_active(self): """Check codec for active messages.""" msg = Message(ID_EOL, 4) v = msg.decode() self.assertTrue(v[0]==ID_EOL and v[1][0]==4, 'ID_EOL broken') msg = Message(ID_EVAL, 'hi mom') v = msg.decode() self.assertTrue(v[0]==ID_EVAL and v[1][0]=='hi mom', 'ID_EVAL broken') msg = Message(ID_EXEC, 'hi mom') v = msg.decode() self.assertTrue(v[0]==ID_EXEC and v[1][0]=='hi mom', 'ID_EXEC broken') msg = Message(ID_GETVAR, 'vvv') v = msg.decode() self.assertTrue(v[0]==ID_GETVAR and v[1][0]=='vvv', 'ID_GETVAR broken') msg = Message(ID_GETSHAPE, 'vvv') v = msg.decode() self.assertTrue(v[0]==ID_GETSHAPE and v[1][0]=='vvv', 'ID_GETSHAPE broken') msg = Message(ID_SETVAR, 'vvv', 31.7) v = msg.decode() self.assertTrue(v[0]==ID_SETVAR and v[1][0]=='vvv' and v[1][1]==31.7, 'ID_SETVAR broken') for ident in [ID_FUNCALL, ID_SUBCALL]: if ident == ID_FUNCALL: err = 'ID_FUNCALL broken' else: err = 'ID_SUBCALL broken' msg = Message(ident, 'vvv') v = msg.decode() self.assertTrue(v[0]==ident and v[1][0]=='vvv' and len(v[1])==1, err+' 1') msg = Message(ident, 'vvv', 31.7) v = msg.decode() self.assertTrue(v[0]==ident and v[1][0]=='vvv' and v[1][1]==31.7, err+' 2') msg = Message(ident, 'vvv', wow=-21) v = msg.decode() self.assertTrue(v[0]==ident and v[1][0]=='vvv' and len(v[1])==1 and v[2]['wow']==-21, err+' 3') msg = Message(ident, 'vvv', 31.7, wow=-21) v = msg.decode() self.assertTrue(v[0]==ident and v[1][0]=='vvv' and v[1][1]==31.7 and v[2]['wow']==-21, err+' 4') msg = Message(ident, 'vvv', 31.7, None, wow=-21, zow='abc') v = msg.decode() self.assertTrue(v[0]==ident and v[1][0]=='vvv' and v[1][1]==31.7 and v[1][2]==None and v[2]['wow']==-21 and v[2]['zow']=='abc', err+' 5') msg = Message(ID_GETSLICE, 'vvv') v = msg.decode() self.assertTrue(v[0]==ID_GETSLICE and v[1][0]=='vvv' and len(v[1])==1, 'ID_GETSLICE broken') msg = Message(ID_GETSLICE, 'vvv', 42, Ellipsis) v = msg.decode() self.assertTrue(v[0]==ID_GETSLICE and v[1][0]=='vvv' and v[1][1]==42 and v[1][2]==Ellipsis, 'ID_GETSLICE broken') msg = Message(ID_SETSLICE, 'vvv', 'q') v = msg.decode() self.assertTrue(v[0]==ID_SETSLICE and v[1][0]=='vvv' and v[1][1]=='q', 'ID_SETSLICE broken 1') msg = Message(ID_SETSLICE, 'vvv', 42, Ellipsis, 'q') v = msg.decode() self.assertTrue(v[0]==ID_SETSLICE and v[1][0]=='vvv' and v[1][1]==42 and v[1][2]==Ellipsis and v[1][3]=='q', 'ID_SETSLICE broken 2') def gen_messages(self): # for test_reader for obj in self.scalars + self.arrays + self.strings + self.groups: yield obj, Message(None, obj) yield 'ID_EOL', Message(ID_EOL, 4) yield 'ID_EVAL', Message(ID_EVAL, 'hi mom') yield 'ID_EXEC', Message(ID_EXEC, 'hi mom') yield 'ID_GETVAR', Message(ID_GETVAR, 'vvv') yield 'ID_GETSHAPE', Message(ID_GETSHAPE, 'vvv') yield 'ID_SETVAR', Message(ID_SETVAR, 'vvv', 31.7) yield 'ID_FUNCALL', Message(ID_FUNCALL, 'vvv', 31.7, None, wow=-21) yield 'ID_SUBCALL', Message(ID_SUBCALL, 'vvv', 31.7, None, wow=-21) yield 'ID_GETSLICE', Message(ID_GETSLICE, 'vvv', 42, Ellipsis) yield 'ID_SETSLICE', Message(ID_SETSLICE, 'vvv', 42, Ellipsis, 'q') def test_reader(self): """Check codec readers.""" for obj, m in self.gen_messages(): mlen = len(m.packets) msg = Message() i = 0 for packet in msg.reader(): em = str(i)+': '+repr(obj) self.assertLess(i, mlen, 'reader stopped late on ' + em) self.assertEqual(packet.dtype.itemsize, m.packets[i].dtype.itemsize, 'reader wrong size on ' + em) # np.copyto(packet, m.packets[i], casting='safe') # following two lines work back to numpy 1.5: self.assertTrue(np.can_cast(m.packets[i].dtype, packet.dtype, casting='safe'), 'reader wrong type on '+ em) packet[...] = m.packets[i] i += 1 self.assertEqual(i, mlen, 'reader stopped early on ' + str(i)+': '+repr(obj)) class TestProcess(unittest.TestCase): def setUp(self): setup_data(self) self.yo = Yorick() def tearDown(self): self.yo.kill() def test_basic(self): """Check variety of simple yorick interface features.""" self.yo("junk=42;") self.assertEqual(self.yo("=junk"), 42, 'process failed basic 1') self.assertEqual(self.yo.v.junk, 42, 'process failed basic 2') self.assertEqual(self.yo.call.junk.v, 42, 'process failed basic 3') self.assertEqual(self.yo.evaluate("junk"), 42, 'process failed basic 4') self.assertEqual(self.yo.handles(1), self.yo.call, 'process failed basic 5') self.assertEqual(self.yo.handles(7), (self.yo.c,self.yo.e,self.yo.v), 'process failed basic 6') self.assertEqual(self.yo.c[''].bare, self.yo.bare, 'process failed basic 7') self.assertEqual(self.yo.v['Y_HOME'], self.yo.v.Y_HOME, 'process failed basic 7') def test_scalars(self): """Check that scalar types can be sent and received.""" for i in range(len(self.scalars)): s = self.scalars[i] self.yo.v.junk = s v = self.yo.v.junk self.assertEqual(s, v, 'process failed on item '+str(i)) def test_arrays(self): """Check that array types can be sent and received.""" for i in range(len(self.arrays)): s = self.arrays[i] self.yo.c.junk = s v = self.yo.e.junk.value self.assertTrue(np.array_equal(np.array(s), v), 'process failed on item '+str(i)) def test_strings(self): """Check that string types can be sent and received.""" for i in range(len(self.strings)): s = self.strings[i] self.yo.e.junk = s v = self.yo.c.junk.value if isinstance(s, np.ndarray): s = s.tolist() self.assertEqual(s, v, 'process failed on item '+str(i)) def test_groups(self): """Check that group types can be sent and received.""" for i in range(len(self.groups)): s = self.groups[i] self.yo.v.junk = s v = self.yo.value.junk if isinstance(s, tuple): s = list(s) elif not len(s): s = [] # yorick cannot distinguish {} from [] self.assertEqual(s, v, 'process failed on item '+str(i)+ '\n'+str(s)+'\n'+str(v)) def test_active(self): """Check that all requests can be sent and received.""" # exec, eval, getvar, setvar already tested above x = self.yo.evaluate.where([1,0,-3]) self.assertEqual(np.array(x).tolist(), [1,3], 'process failed on funcall') self.yo(""" func test(a, b=) { extern testv; testv = a - b; return testv; } """) self.assertEqual(self.yo.e("test({0}, b={1})", [2,1], 1.5).tolist(), [0.5, -0.5], 'process failed on formatted eval') f = self.yo.value.test self.assertTrue(isinstance(f, YorickVar), 'process failed on non-data value return') self.yo.call.test([1,2], b=1.5) self.assertEqual(self.yo.v.testv.tolist(), [-0.5, 0.5], 'process failed on subcall with keyword') self.assertTrue(f([2,1], b=1.5) is None, 'process failed on value subcall semantics') self.assertEqual(self.yo.v.testv.tolist(), [0.5, -0.5], 'process failed on value subcall with keyword') self.assertEqual(self.yo.e.test([1,2], b=1.5).tolist(), [-0.5, 0.5], 'process failed on funcall with keyword') self.assertEqual(self.yo.e.testv[1], -0.5, 'process failed on getslice') self.assertEqual(self.yo.e.testv[...].tolist(), [-0.5, 0.5], 'process failed on getslice with ellipsis') self.yo.e.testv[1:2] = [2.0, 3.0] self.assertEqual(self.yo.v.testv.tolist(), [2.0, 3.0], 'process failed on setslice') self.yo.c.testv[0:] = [3.0, 2.0] self.assertEqual(self.yo.v.testv.tolist(), [3.0, 2.0], 'process failed on setslice, python semantics') i = self.yo.evaluate.testv.info self.assertEqual(i, (6, 1, 2), 'process failed on getshape') i = self.yo.evaluate.test.info self.assertEqual(i, (-1,), 'process failed on getshape') def test_hold(self): """Check that all requests can be sent and received.""" # exec, eval, getvar, setvar already tested above #f = self.yo.e.create('~/gh/pyorick/junk') #self.yo.e.write(f, 'this is a test') #del f self.yo(""" struct PyTest { long mema; double memb(2,3); char memc; } """) struct = self.yo.e.PyTest(mema=-7, memb=[[11,12],[21,22],[31,32]], memc=65) self.assertEqual(struct['mema'], -7, 'string valued index failed') self.assertEqual(struct['memb',2,3], 32, 'string mixed index failed') s = Key2AttrWrapper(struct) self.assertEqual(s.memc, 65, 'Key2AttrWrapper get failed') s.memc = 97 self.assertEqual(s.memc, 97, 'Key2AttrWrapper set failed') s = self.yo.e.random.hold(1000, 1001) self.assertTrue(isinstance(s, YorickVar), 'hold attribute failed') del struct # checks that deleting held reference works self.yo.v.t = self.yo.e.noop(s) self.assertEqual(self.yo.e.t.shape, (1001,1000), 'passing held reference as argument failed') s = s[5,None] # implicitly deletes object after retrieving one column self.assertEqual(s.shape, (1001,), 'indexing held reference failed') s = self.yo.e('@t') self.assertTrue(isinstance(s, YorickVar), 'hold @-syntax failed') self.assertEqual(s.shape, (1001,1000), 'held reference attribute failed') del s self.yo.v.t = None def test_recurse(self): """Check that a yorick reply can contain python requests.""" self.yo(""" func recursive(x) { extern _recur; if (!_recur) { _recur=1; py, "import numpy as np"; } y = py("np.array", [x, 1-x]); py, "var=", 1+x; return py("var") - x; } """) self.yo.c.recursive(2) self.assertEqual(__main__.var, 3, 'recursive request set failed') self.assertEqual(self.yo.e.recursive(2), 1, 'recursive request reply value failed') if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1713914522.5577576 pyorick-1.5/pyorick.egg-info/0000775000175000017500000000000000000000000016074 5ustar00davedave00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1713914522.0 pyorick-1.5/pyorick.egg-info/PKG-INFO0000644000175000017500000000310300000000000017164 0ustar00davedave00000000000000Metadata-Version: 2.1 Name: pyorick Version: 1.5 Summary: python connection to yorick Home-page: https://github.com/dhmunro/pyorick Author: David Munro and John Field Author-email: dhmunro@users.sourceforge.net License: http://opensource.org/licenses/BSD-2-Clause Platform: Linux Platform: MacOS X Platform: Unix Classifier: License :: OSI Approved :: BSD License Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Operating System :: POSIX :: Linux Classifier: Operating System :: MacOS :: MacOS X Classifier: Operating System :: Unix Classifier: Topic :: Scientific/Engineering Classifier: Topic :: Software Development :: Interpreters Requires: numpy License-File: LICENSE.txt Run Yorick from Python ====================== The pyorick package starts `yorick `_ as a subprocess and provides an interface between python and yorick interpreted code. Features: - exec or eval arbitrary yorick code strings - get or set yorick variables - call yorick functions or subroutines with python arguments - get or set slices of large yorick arrays - terminal mode to interact with yorick by keyboard through python Most of the data is exchanged via binary pipes between the two interpreters. Yorick runs in a request-reply mode. Python prints anything yorick sends to stdout or stderr except prompts. See `DESCRIPTION.rst `_ for a complete description of the interface. You can clone or fork https://github.com/dhmunro/pyorick to contribute to pyorick. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1713914522.0 pyorick-1.5/pyorick.egg-info/SOURCES.txt0000664000175000017500000000041100000000000017754 0ustar00davedave00000000000000DESCRIPTION.rst LICENSE.txt MANIFEST.in README.rst setup.py pyorick/__init__.py pyorick/pyorick.i0 pyorick/pyorick.py pyorick/test_pyorick.py pyorick.egg-info/PKG-INFO pyorick.egg-info/SOURCES.txt pyorick.egg-info/dependency_links.txt pyorick.egg-info/top_level.txt././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1713914522.0 pyorick-1.5/pyorick.egg-info/dependency_links.txt0000664000175000017500000000000100000000000022142 0ustar00davedave00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1713914522.0 pyorick-1.5/pyorick.egg-info/top_level.txt0000664000175000017500000000001000000000000020615 0ustar00davedave00000000000000pyorick ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1713914522.5577576 pyorick-1.5/setup.cfg0000664000175000017500000000004600000000000014543 0ustar00davedave00000000000000[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1713903938.0 pyorick-1.5/setup.py0000664000175000017500000000426700000000000014445 0ustar00davedave00000000000000#!/usr/bin/env python from __future__ import print_function from distutils.core import setup, Command class TestCommand(Command): description = "PYorick test/check command" user_options = [] def get_command_name(self): return "test" def initialize_options(self): pass def finalize_options(self): pass def run(self): try: import pyorick.test_pyorick as testmod import unittest for c in [testmod.TestProcess, testmod.TestCodec]: print("Testing", str(c)) suite = unittest.TestLoader().loadTestsFromTestCase(c) unittest.TextTestRunner(verbosity=2).run(suite) except Exception as e : raiseNameError("setup.py test: error in test\nException: {0}".format(e)) return # This package requires the yorick startup file pyorick.i0 to be # installed as an ordinary file in the same directory as pyorick.py. # Even if you have no way to install python packages, you can # make pyorick.py work by creating a directory, copying pyorick.py # and pyorick.i0 to that directory, and adding the directory to # your PYTHONPATH environment variable. You can optionally copy # test_pyorick.py to the same directory, cd there, and run nosetests # or py.test or python -m unittest -v test_pyorick to test pyorick. setup(name='pyorick', version='1.5', description='python connection to yorick', long_description=open('README.rst').read(), author='David Munro and John Field', author_email='dhmunro@users.sourceforge.net', url='https://github.com/dhmunro/pyorick', packages=['pyorick'], package_data={'pyorick': ['pyorick.i0']}, requires=['numpy'], license='http://opensource.org/licenses/BSD-2-Clause', platforms=['Linux', 'MacOS X', 'Unix'], classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Unix', 'Topic :: Scientific/Engineering', 'Topic :: Software Development :: Interpreters', ], cmdclass = {'test': TestCommand}, )