PIMS  

Tutorial

Table of Content

This tutorial briefly explains how to use PIMS

Modules

To use Python function or objects, we need to import modules.
The command pyImport() is used for that purpose.

For example, to import the math module, which is installed with Python:

pyImport math;

For the Python builtin module, it is imported with the specific command:

py = pyBuiltin();

For custom modules, pyAddToPath() is used to specify the module location.

Functions

The available methods of a module are listed with the pyGetMethods() command.
For the imported math module:

pyGetMethods(math)

A function is called by prefixing it with the module name.
For example with the math module:

b = math.sqrt(144)

And with the builtin module:

i = int32(15); // need to convert 15 which is a double in Scilab
h = py.hex(i)

Any python function can be mapped to a Scilab function with the pyDeff() function:

hex = pyDeff("builtin", "hex", "pyHex");
h = pyHex(i)

Or invoked with the pyInvoke() command:

hex = pyGetAttr(py, "hex");
h = pyInvoke(hex, i)

Variables, types

pyWrap() converts a Scilab variable to Python.

For example, to convert a Scilab matrix:

a = [1, 2, 0];
pa = pyWrap(a);
b = py.sum(pa)

pyUnwrap() does the reverse of pyWrap().

Python dictionaries, tuples, sets,... can also be created with dedicated functions.

The pyDict() command creates a Python dictionary:

dict = pyDict("type", "vector", "name", "x", "value", [0, 3])

For a tuple, the pyTuple() is used:

t = pyTuple(1.0, 2.0, 6.0);
m = py.max(t)

Python classes can also be instancied and manipulated.

Example

Let's finish by a small example that saves/loads some data to/from a JSON file.

// get builtin functions
py = pyBuiltin();

// create data
person1 = pyDict("name", "joe", "age", "21");
person2 = pyDict("name", "bill", "age", "47");
person3 = pyDict("name", "mary", "age", "32");

persons_write = pyTuple(person1, person2, person3);

// save data
pyImport json;

filename = TMPDIR + '/persons.json';
f = py.open(filename, 'w');
json.dump(personsl_write, f);
f.close();

// load data
f = py.open(filename, 'r');
lines = f.readlines();
persons_read = json.loads(lines);
f.close();

// delete file
pyImport os;
os.remove(filename);

// print data
person = persons_read(0);
person_name = person.name.encode('ascii');
person_age = strtod(person.age.encode('ascii'));
mprintf("First person name is ''%s'' and is %d years old.", person_name, person_age);

Created: 4 years 7 months ago
by Simon Marchetto

Updated: 1 year 11 months ago
by Simon Marchetto

Old Revisions