# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import xmlrpclib,sys
+import xmlrpc.client,sys
data="""
<methodCall>
</methodCall>
"""
def echo(args):
- print args
+ print(args)
return 96785439
f=open("input")
data=f.read()
f.close()
-params, method = xmlrpclib.loads(data)
+params, method = xmlrpc.client.loads(data)
try:
call=eval(method)
response = (response,)
except:
# report exception back to server
- response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % sys.exc_info()[:2]))
+ response = xmlrpc.client.dumps( xmlrpc.client.Fault(1, "%s:%s" % sys.exc_info()[:2]))
else:
- response = xmlrpclib.dumps( response, methodresponse=1)
+ response = xmlrpc.client.dumps( response, methodresponse=1)
-print response
+print(response)
f=open("output",'w')
f.write(response)
f.close()
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright (C) 2006-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
"""Doxygen XML to SWIG docstring converter.
-Usage:
-
- doxy2swig.py [options] input.xml output.i
-
Converts Doxygen generated XML files into a file containing docstrings
that can be used by SWIG-1.3.x. Note that you need to get SWIG
version > 1.3.23 or use Robin Dunn's docstring patch to be able to use
output will be written (the file will be clobbered).
"""
+
+__usage__ = "doxy2swig.py [options] input.xml output.i"
######################################################################
#
# This code is implemented using Mark Pilgrim's code as a guideline:
import sys
import types
import os.path
-import optparse
+import argparse
def my_open_read(source):
if hasattr(source, "read"):
return source
else:
- return open(source)
+ return open(source, encoding='utf8')
def my_open_write(dest):
if hasattr(dest, "write"):
return dest
else:
- return open(dest, 'w')
+ return open(dest, 'w', encoding='utf8')
class Doxy2SWIG:
def add_text(self, value):
"""Adds text corresponding to `value` into `self.pieces`."""
- if type(value) in (types.ListType, types.TupleType):
+ if type(value) in (list, tuple):
self.pieces.extend(value)
else:
self.pieces.append(value)
kind = node.attributes['kind'].value
if kind in ('class', 'struct'):
prot = node.attributes['prot'].value
- if prot <> 'public':
+ if prot != 'public':
return
names = ('compoundname', 'briefdescription',
'detaileddescription', 'includes')
first = self.get_specific_nodes(node, names)
for n in names:
- if first.has_key(n):
+ if n in first:
self.parse(first[n])
self.add_text(['";','\n'])
for n in node.childNodes:
- if n not in first.values():
+ if n not in list(first.values()):
self.parse(n)
elif kind in ('file', 'namespace'):
nodes = node.getElementsByTagName('sectiondef')
def do_parameterlist(self, node):
text='unknown'
- for key, val in node.attributes.items():
+ for key, val in list(node.attributes.items()):
if key == 'kind':
if val == 'param': text = 'Parameters'
elif val == 'exception': text = 'Exceptions'
if name[:8] == 'operator': # Don't handle operators yet.
return
- if not first.has_key('definition') or \
+ if 'definition' not in first or \
kind in ['variable', 'typedef']:
return
self.add_text(' %s::%s "\n%s'%(cname, name, defn))
for n in node.childNodes:
- if n not in first.values():
+ if n not in list(first.values()):
self.parse(n)
self.add_text(['";', '\n'])
if not os.path.exists(fname):
fname = os.path.join(self.my_dir, fname)
if not self.quiet:
- print "parsing file: %s"%fname
+ print("parsing file: %s"%fname)
p = Doxy2SWIG(fname, self.include_function_definition, self.quiet)
p.generate()
self.pieces.extend(self.clean_pieces(p.pieces))
p.write(output)
def main():
- usage = __doc__
- parser = optparse.OptionParser(usage)
- parser.add_option("-n", '--no-function-definition',
- action='store_true',
- default=False,
- dest='func_def',
- help='do not include doxygen function definitions')
- parser.add_option("-q", '--quiet',
- action='store_true',
- default=False,
- dest='quiet',
- help='be quiet and minimise output')
+ parser = argparse.ArgumentParser(description=__doc__, usage = __usage__)
+ parser.add_argument("-n", '--no-function-definition',
+ action='store_true',
+ default=False,
+ dest='func_def',
+ help='do not include doxygen function definitions')
+ parser.add_argument("-q", '--quiet',
+ action='store_true',
+ default=False,
+ dest='quiet',
+ help='be quiet and minimise output')
+ parser.add_argument('input')
+ parser.add_argument('ouput')
- options, args = parser.parse_args()
- if len(args) != 2:
- parser.error("error: no input and output specified")
+ args = parser.parse_args()
- convert(args[0], args[1], not options.func_def, options.quiet)
+ convert(args.input, args.output, not options.func_def, options.quiet)
if __name__ == '__main__':
description:
-- Import test_schema.xml
-- Select block node "bbb" => modify its parameters as:
- · Delete "node4" from first line
- · Create new line by "+" pressing
- · Add "nnode0"
+ · Delete "node4" from first line
+ · Create new line by "+" pressing
+ · Add "nnode0"
-- Press Apply button
Result: SIGSEGV
comments: OCC: DONE
description:
-- Import test_schema_last.xml
-- Select node "node1" => modify its parameters as:
- · Change name
- · Assign new valyes to X and Y
+ · Change name
+ · Assign new valyes to X and Y
-- Press Apply button
-- Select in 2D Viewer block node"Sb1", for which previous node belongs
Result: SIGSEGV
TODOlist, questions
-------------------
-Les noms de noeuds devraient avoir une portée relative au bloc qui les contient,
-et pouvoir être identifiés au sein d'une hiérarchie de bloc par un nom
-construit de la même façon que pour les ports:
+Les noms de noeuds devraient avoir une portée relative au bloc qui les contient,
+et pouvoir être identifiés au sein d'une hiérarchie de bloc par un nom
+construit de la même façon que pour les ports:
"bloc1.bloc2.noeud3"
-Dans quels cas faut-il créer des ports de données sur des noeuds composés ?
+Dans quels cas faut-il créer des ports de données sur des noeuds composés ?
(Switch, boucle...).
-La création est elle faite automatiquement au niveau de l'engine ?
+La création est elle faite automatiquement au niveau de l'engine ?
-Fonction de vérification de la compétude d'un graphe à l'édition:
-- tous les ports de donnée entrants doivent être initialisés ou connectés.
-- inventaire des ports de donnée entrants non initialisés et non connectés.
-- faut-il vérifier quelque chose pour les gates ?
+Fonction de vérification de la compétude d'un graphe à l'édition:
+- tous les ports de donnée entrants doivent être initialisés ou connectés.
+- inventaire des ports de donnée entrants non initialisés et non connectés.
+- faut-il vérifier quelque chose pour les gates ?
-Regles d'ecriture C++ à definir :
+Regles d'ecriture C++ à definir :
- pas de clause using namespace dans les .hxx
- prefixer les attributs de classe par _
- indentation style gnu
- utilisation des namespace dans les cxx
- - nom complets dans les declarations (identité avec .hxx pour doxygen)
+ - nom complets dans les declarations (identité avec .hxx pour doxygen)
IMPROVEMENTS :
- test foreach4.xml problemes sporadiques (CC) sur conversions de doubles
- ecriture graphe XML :
- - ajout attribut _isComponentMethod initialisé a true pour noeuds SALOME
+ - ajout attribut _isComponentMethod initialisé a true pour noeuds SALOME
est-ce utile ?
- <node>/<component> dans bschema, cschema, dschema...
- calcium*.xml
The Python protocol
++++++++++++++++++++++
-The Python protocol is based on serialisation done by the cPickle module (C implementation of the pickle module).
+The Python protocol is based on serialisation done by the pickle module.
All that is necessary is to define an object reference type with the Python protocol so that Python objects
can be exchanged between Python inline nodes and with SALOME components implemented in Python.
SALOME components implemented in Python that are required to support this exchange type must be designed
way as the example in the run method described below::
def run(self,s):
- o=cPickle.loads(s)
+ o=pickle.loads(s)
ret={'a':6, 'b':[1,2,3]}
- return cPickle.dumps(ret,-1)
+ return pickle.dumps(ret,-1)
The json protocol
++++++++++++++++++++++
The json protocol is based on `JSON <http://www.json.org/>`_ (JavaScript Object Notation)
-serialisation / deserialisation instead of cPickle. JSON supports fewer data types and requires that
+serialisation / deserialisation instead of pickle. JSON supports fewer data types and requires that
the simplejson Python module should be installed, but it has the advantage that it is more interoperable.
In particular, there are C++ libraries that serialise/deserialise the JSON.
C = compo.compo()
z = C.addvec(x, y)
-print 'x = ', x
-print 'y = ', y
-print 'z = ', z
-print C.prdscl(x,y)
+print('x = ', x)
+print('y = ', y)
+print('z = ', z)
+print(C.prdscl(x,y))
S = systeme.Systeme()
-print "create U1 ..."
+print("create U1 ...")
S.touch('U1')
-print "dir : ", S.dir()
+print("dir : ", S.dir())
-print "copy U1 to U2 ..."
+print("copy U1 to U2 ...")
S.cp('U1', 'U2')
-print "dir : ", S.dir()
+print("dir : ", S.dir())
-print "delete U1 ..."
+print("delete U1 ...")
S.rm('U1')
-print "dir : ", S.dir()
+print("dir : ", S.dir())
-print "delete U2 ..."
+print("delete U2 ...")
S.rm('U2')
-print "dir : ", S.dir()
+print("dir : ", S.dir())
v2 = [ 3, 4, 5 ]
v3 = o.addvec(v1, v2)
-print v3
+print(v3)
-print o.prdscl(v1, v3)
+print(o.prdscl(v1, v3))
import sys, os, string, py_compile
files = '''$*'''
-print 'Byte-compiling python modules...'
+print('Byte-compiling python modules...')
for file in string.split(files):
$trans
if not os.path.exists(path) or not (len(path) >= 3 and path[-3:] == '.py'):
continue
- print file,
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(path)
print" || exit $?
import sys, os, string, py_compile
files = '''$*'''
-print 'Byte-compiling python modules (optimised versions) ...'
+print('Byte-compiling python modules (optimised versions) ...')
for file in string.split(files):
$trans
if not os.path.exists(path) or not (len(path) >= 3 and path[-3:] == '.py'):
continue
- print file,
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(path)
print" 2>/dev/null || :
#define ROSENBROCK
-/* constante dépendant du choix de l'évaluateur */
+/* constante dépendant du choix de l'évaluateur */
-// nombre de paramètre
+// nombre de paramètre
#ifdef GRIEWANK
#define NBGENE 30
#else
INCLUDE_DIRECTORIES(
${PTHREAD_INCLUDE_DIR}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PYTHON_INCLUDE_DIRS}
${PROJECT_BINARY_DIR}/idl
${PROJECT_BINARY_DIR}
#ifdef OMNIORB
#include <omniORB4/CORBA.h>
-//--- from omniORBpy.h (not present on Debian Sarge packages)
-struct omniORBPYAPI
-{
- PyObject* (*cxxObjRefToPyObjRef)(const CORBA::Object_ptr cxx_obj,
- CORBA::Boolean hold_lock);
- // Convert a C++ object reference to a Python object reference.
- // If <hold_lock> is true, caller holds the Python interpreter lock.
-
- CORBA::Object_ptr (*pyObjRefToCxxObjRef)(PyObject* py_obj,
- CORBA::Boolean hold_lock);
- // Convert a Python object reference to a C++ object reference.
- // Raises BAD_PARAM if the Python object is not an object reference.
- // If <hold_lock> is true, caller holds the Python interpreter lock.
-
- PyObject* (*handleCxxSystemException)(const CORBA::SystemException& ex);
- // Sets the Python exception state to reflect the given C++ system
- // exception. Always returns NULL. The caller must hold the Python
- // interpreter lock.
-};
-
-omniORBPYAPI* api;
+#include <omniORBpy.h>
+omniORBpyAPI* api=0;
#define OMNIPY_CATCH_AND_HANDLE_SYSTEM_EXCEPTIONS \
catch (const CORBA::SystemException& ex) { \
To overload standard SWIG wrapping we define a full specialization of std::map
with %extend for 4 basic methods : getitem, setitem, delitem and keys.
Then we complete the interface by deriving the shadow wrapper from
- the python mixin class (UserDict.DictMixin).
+ the python mixin class (UserDict.DictMixin / collections.MutableMapping with Python 3).
Do not forget to declare the new shadow class to SWIG with tname_swigregister(tname).
Objects returned by __getitem__ are declared new (%newobject) so that when destroyed they
call decrRef (see feature("unref") for RefCounter).
%template() std::pair<std::string, T* >;
%template(tname) std::map<std::string, T* >;
%pythoncode{
-from UserDict import DictMixin
-class tname(tname,DictMixin):pass
+from collections import MutableMapping
+class tname(tname,MutableMapping):pass
tname##_swigregister(tname)
}
%enddef
if (!omnipy)
{
PyErr_SetString(PyExc_ImportError,(char*)"Cannot import _omnipy");
- return;
+ return NULL;
}
PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
- api = (omniORBPYAPI*)PyCObject_AsVoidPtr(pyapi);
+ api = (omniORBpyAPI*)PyCapsule_GetPointer(pyapi,"_omnipy.API");
Py_DECREF(pyapi);
#endif
%}
// param 0
PyObject *ret0Py(PyList_New(ret0.size()));
for(std::size_t i=0;i<ret0.size();i++)
- PyList_SetItem(ret0Py,i,PyInt_FromLong(ret0[i]));
+ PyList_SetItem(ret0Py,i,PyLong_FromLong(ret0[i]));
PyTuple_SetItem(ret,0,ret0Py);
// param 1
PyObject *ret1Py(PyList_New(ret1.size()));
// param 2
PyObject *ret2Py(PyList_New(ret2.size()));
for(std::size_t i=0;i<ret2.size();i++)
- PyList_SetItem(ret2Py,i,PyString_FromString(ret2[i].c_str()));
+ PyList_SetItem(ret2Py,i,PyBytes_FromString(ret2[i].c_str()));
PyTuple_SetItem(ret,2,ret2Py);
return ret;
}
if (!omnipy)
{
PyErr_SetString(PyExc_ImportError,(char*)"Cannot import _omnipy");
- return;
+ return NULL;
}
PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
- api = (omniORBPYAPI*)PyCObject_AsVoidPtr(pyapi);
+ api = (omniORBpyAPI*)PyCapsule_GetPointer(pyapi,"_omnipy.API");
Py_DECREF(pyapi);
#endif
%}
# additional include directories
INCLUDE_DIRECTORIES(
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PYTHON_INCLUDE_DIR}
${PROJECT_SOURCE_DIR}/src/bases
${PROJECT_SOURCE_DIR}/src/engine
throw YACS::Exception("YACSEvalInputPort::getDefaultValueDefined : internal error !");
if(PyFloat_Check(data))
return new YACSEvalAnyDouble(PyFloat_AsDouble(data));
- if(PyInt_Check(data))
- return new YACSEvalAnyInt((int)PyInt_AsLong(data));
+ if(PyLong_Check(data))
+ return new YACSEvalAnyInt((int)PyLong_AsLong(data));
throw YACS::Exception("YACSEvalInputPort::getDefaultValueDefined : unmanaged types different from int and double for py !");
}
YACS::ENGINE::AnyInputPort *i1(dynamic_cast<YACS::ENGINE::AnyInputPort *>(_ptr));
}
else if(par1)
{
- PyObject *obj(PyInt_FromLong(par1->toInt()));
+ PyObject *obj(PyLong_FromLong(par1->toInt()));
i0->put(obj);
Py_XDECREF(obj);
}
-// Copyright (C) 2012-2016 CEA/DEN, EDF R&D
+ // Copyright (C) 2012-2016 CEA/DEN, EDF R&D
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
PyObject *ob(PyList_New(sz));
for(std::size_t i=0;i<sz;i++)
{
- PyList_SetItem(ob,i,PyInt_FromLong((*_arr)[i]));
+ PyList_SetItem(ob,i,PyLong_FromLong((*_arr)[i]));
}
p->put(ob);
p->exSaveInit();
_salomeInstance=PyObject_Call(startMeth,myArgs,myKWArgs);//new
YACS::ENGINE::AutoPyRef getPortMeth(PyObject_GetAttrString(_salomeInstance,const_cast<char *>("get_port")));//new
YACS::ENGINE::AutoPyRef portPy(PyObject_CallObject(getPortMeth,0));//new
- _port=PyInt_AsLong(portPy);
+ _port=PyLong_AsLong(portPy);
//
int dummy;
_corbaConfigFileName=GetConfigAndPort(dummy);
PyObject *kernelRootDir(0);// os.environ["KERNEL_ROOT_DIR"]
{
YACS::ENGINE::AutoPyRef environPy(PyObject_GetAttrString(osPy,const_cast<char *>("environ")));//new
- YACS::ENGINE::AutoPyRef kernelRootDirStr(PyString_FromString(const_cast<char *>(KERNEL_ROOT_DIR)));//new
+ YACS::ENGINE::AutoPyRef kernelRootDirStr(PyBytes_FromString(const_cast<char *>(KERNEL_ROOT_DIR)));//new
kernelRootDir=PyObject_GetItem(environPy,kernelRootDirStr);//new
}
{
YACS::ENGINE::AutoPyRef joinPy(PyObject_GetAttrString(pathPy,const_cast<char *>("join")));//new
YACS::ENGINE::AutoPyRef myArgs(PyTuple_New(4));
Py_XINCREF(kernelRootDir); PyTuple_SetItem(myArgs,0,kernelRootDir);
- PyTuple_SetItem(myArgs,1,PyString_FromString(const_cast<char *>("bin")));
- PyTuple_SetItem(myArgs,2,PyString_FromString(const_cast<char *>("salome")));
- PyTuple_SetItem(myArgs,3,PyString_FromString(const_cast<char *>("appliskel")));
+ PyTuple_SetItem(myArgs,1,PyBytes_FromString(const_cast<char *>("bin")));
+ PyTuple_SetItem(myArgs,2,PyBytes_FromString(const_cast<char *>("salome")));
+ PyTuple_SetItem(myArgs,3,PyBytes_FromString(const_cast<char *>("appliskel")));
YACS::ENGINE::AutoPyRef res(PyObject_CallObject(joinPy,myArgs));
- ret=PyString_AsString(res);
+ ret=PyBytes_AsString(res);
}
Py_XDECREF(kernelRootDir);
return ret;
YACS::ENGINE::AutoPyRef osPy(PyImport_ImportModule(const_cast<char *>("os")));//new
YACS::ENGINE::AutoPyRef environPy(PyObject_GetAttrString(osPy,const_cast<char *>("environ")));//new
//
- YACS::ENGINE::AutoPyRef corbaConfigStr(PyString_FromString(const_cast<char *>(CORBA_CONFIG_ENV_VAR_NAME)));//new
+ YACS::ENGINE::AutoPyRef corbaConfigStr(PyBytes_FromString(const_cast<char *>(CORBA_CONFIG_ENV_VAR_NAME)));//new
YACS::ENGINE::AutoPyRef corbaConfigFileNamePy(PyObject_GetItem(environPy,corbaConfigStr));//new
- std::string ret(PyString_AsString(corbaConfigFileNamePy));
+ std::string ret(PyBytes_AsString(corbaConfigFileNamePy));
//
- YACS::ENGINE::AutoPyRef nsPortStr(PyString_FromString(const_cast<char *>(NSPORT_VAR_NAME)));//new
+ YACS::ENGINE::AutoPyRef nsPortStr(PyBytes_FromString(const_cast<char *>(NSPORT_VAR_NAME)));//new
YACS::ENGINE::AutoPyRef nsPortValuePy(PyObject_GetItem(environPy,nsPortStr));//new
- std::string portStr(PyString_AsString(nsPortValuePy));
+ std::string portStr(PyBytes_AsString(nsPortValuePy));
std::istringstream iss(portStr);
iss >> port;
return ret;
const char fetchPyCmd[]="import salome,CORBA\nsalome.salome_init()\nsl=salome.naming_service.Resolve(\"/SalomeLauncher\")\nif not CORBA.is_nil(sl):\n return salome.orb.object_to_string(sl)\nelse:\n raise Exception(\"Impossible to locate salome launcher !\")";
YACS::ENGINE::AutoPyRef func(YACS::ENGINE::evalPy(methName,fetchPyCmd));
YACS::ENGINE::AutoPyRef val(YACS::ENGINE::evalFuncPyWithNoParams(func));
- std::string ior(PyString_AsString(val));
+ std::string ior(PyBytes_AsString(val));
CORBA::Object_var obj(string_to_object(ior));
if(CORBA::is_nil(obj))
throw YACS::Exception("goFetchingSalomeLauncherInNS : fetched ior is NIL !");
for(std::size_t i=0;i<sz;i++)
{
PyObject *elt(PyList_GetItem(obj,i));
- eltCpp[i]=PyInt_AsLong(elt);
+ eltCpp[i]=PyLong_AsLong(elt);
}
YACS::AutoCppPtr<YACSEvalSeqAnyInt> elt(new YACSEvalSeqAnyInt(eltCpp));
return elt.dettach();
//
YACS::ENGINE::AutoPyRef func(YACS::ENGINE::evalPy(EFXGenFileName,EFXGenContent));
YACS::ENGINE::AutoPyRef val(YACS::ENGINE::evalFuncPyWithNoParams(func));
- _locSchemaFile=PyString_AsString(val);
+ _locSchemaFile=PyBytes_AsString(val);
func=YACS::ENGINE::evalPy(EFXGenFileName,EFXGenContent2);
val=YACS::ENGINE::evalFuncPyWithNoParams(func);
- _jobName=PyString_AsString(val);
+ _jobName=PyBytes_AsString(val);
//
static const char LISTPYOBJ_STR[]="list[pyobj]";
if(getBoss()->getOutputsOfInterest().empty())
${PROJECT_SOURCE_DIR}/src/yacsloader_swig
${PROJECT_SOURCE_DIR}/src/evalyfx
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PYTHON_INCLUDE_DIRS}
)
PyObject *o=PyList_GetItem(pyLi,i);
if(PyInt_Check(o))
{
- int val=(int)PyInt_AS_LONG(o);
+ int val=(int)PyLong_AS_LONG(o);
arr[i]=val;
}
else
for(int i=0;i<size;i++)
{
PyObject *o=PyTuple_GetItem(pyLi,i);
- if(PyInt_Check(o))
+ if(PyLong_Check(o))
{
- int val=(int)PyInt_AS_LONG(o);
+ int val=(int)PyLong_AS_LONG(o);
arr[i]=val;
}
else
std::size_t sz(arr.size());
PyObject *ret(PyList_New(sz));
for(std::size_t i=0;i<sz;i++)
- PyList_SetItem(ret,i,PyInt_FromLong(arr[i]));
+ PyList_SetItem(ret,i,PyLong_FromLong(arr[i]));
return ret;
}
std::size_t sz2(zeArr->size());
PyObject *ret2(PyList_New(sz2));
for(std::size_t i2=0;i2<sz2;i2++)
- PyList_SetItem(ret2,i2,PyInt_FromLong((*zeArr)[i2]));
+ PyList_SetItem(ret2,i2,PyLong_FromLong((*zeArr)[i2]));
PyList_SetItem(ret,i,ret2);
}
else
}
else if(PyInt_Check(parameter))
{
- YACSEvalAnyInt tmp((int)PyInt_AsLong(parameter));
+ YACSEvalAnyInt tmp((int)PyLong_AsLong(parameter));
self->setDefaultValue(&tmp);
}
else
PyObject *ret0Py(ret0?Py_True:Py_False);
Py_XINCREF(ret0Py);
PyTuple_SetItem(ret,0,ret0Py);
- PyTuple_SetItem(ret,1,PyInt_FromLong(ret1));
+ PyTuple_SetItem(ret,1,PyLong_FromLong(ret1));
return ret;
}
}
cp.setWCKey("P11U50:CARBONES") ; cp.setNbProcs(5) ; cp.setMaxDuration("00:05")
assert(not rss.isInteractive())
a,b=efx.run(session)
-print("************",a,b)
-print efx.getResults()
+print(("************",a,b))
+print(efx.getResults())
INCLUDE_DIRECTORIES(
${PYTHON_INCLUDE_DIR}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${LIBXML2_INCLUDE_DIR}
${GRAPHVIZ_INCLUDE_DIRS}
${QT_INCLUDES}
void FormContainerDecorator::connectForTyp()
{
connect(_typ->cb_resource,SIGNAL(mousePressed()),this,SLOT(onResMousePressed()));
- connect(_typ->cb_resource,SIGNAL(activated(int)),this,SLOT(onResActivated));
- connect(tb_container,SIGNAL(toggled(bool)),this,SLOT(onContToggled()));
+ connect(_typ->cb_resource,SIGNAL(activated(int)),this,SLOT(onResActivated(int)));
+ connect(tb_container,SIGNAL(toggled(bool)),this,SLOT(onContToggled(bool)));
}
</widget>
</item>
<item>
- <widget class="QComboBox" name="cb_resource">
+ <widget class="ComboBox" name="cb_resource">
<property name="toolTip">
<string>name of the resource hosting container when manually set</string>
</property>
</item>
</layout>
</widget>
+ <customwidgets>
+ <customwidget>
+ <class>ComboBox</class>
+ <extends>QComboBox</extends>
+ <header>FormComponent.hxx</header>
+ </customwidget>
+ </customwidgets>
<resources/>
<connections/>
</ui>
#include <iostream>
#include <fstream>
-#include "ListJobs_GUI.hxx"
#include "RuntimeSALOME.hxx"
+#include "ListJobs_GUI.hxx"
#include "GenericGui.hxx"
#include "QtGuiContext.hxx"
#include "YACSGuiLoader.hxx"
void SceneComposedNodeItem::shrinkExpandRecursive(bool toExpand, bool fromHere, ShrinkMode theShrinkMode)
{
- DEBTRACE("SceneComposedNodeItem::shrinkExpandRecursive " << isExpanding << " " << fromHere << " " << isExpanded() << " " << _label.toStdString());
+ DEBTRACE("SceneComposedNodeItem::shrinkExpandRecursive " << toExpand << " " << fromHere << " " << isExpanded() << " " << _label.toStdString());
bool toChangeShrinkState = false;
switch (theShrinkMode) {
x sauvegarde schema en edition
x import catalogues depuis schemas
x insertion dans SALOME 5
-x boutons-actions zoom, panning, cadre zone à voir, reset vue, fit all
+x boutons-actions zoom, panning, cadre zone à voir, reset vue, fit all
x proc remplit automatiquement toute la vue principale (bouton fit all)
x bouton save ou save as au lieu de export
x Model/view table (ports)
x affichage etat en edition
-x dessins des liens de contrôle
+x dessins des liens de contrôle
x gestion etude SALOME : object browser
x design arbre (edition/execution)
x contournement bug confirmOverwrite QFileDialog Qt 4.3.3 (corrige en 4.3.5)
- drag & drop de ports pour l'ordre dans le tableau, dans la scene
- creation de liens par menu
-x distinguer les liens simples (sans contrôle)
+x distinguer les liens simples (sans contrôle)
- deplacement de noeud a la souris: pouvoir passer par dessus un bloc
(pressed + touche...) transparence, finir le deplacement que s'il y a
la place, ou pousser le bloc ?
- choix d'un port dans le panneau noeud -> arbre, vue
- selection multiples (arbre, tableau vue) pour action groupee
(deplacement scene, destruction...)
-- connexion automatique de ports avec des noeuds bord à bord
+- connexion automatique de ports avec des noeuds bord à bord
(regle de correspondance de noms ? respect de l'ordre ?)
- dessiner les liens avec des ponts quand des liens se croisent !
- 2eme vue avec schema complet et cadre de la vue principale
x message incomprehensible lors de l'ajout d'un deuxieme noeud dans un forloop
x libelle comboBox ajout de ports dans panneau edition: folklorique (newSchema_1)
x fermeture schema non sauvegarde : dialogues de sauvegarde
-x lien nouvellement créé droit et très fin, pas toujours visible
+x lien nouvellement créé droit et très fin, pas toujours visible
x panneau edition function Node: controler nom de fonction saisie (validation)
x panneau edition function Node: remonter le nom de fonction
x remontee d'erreur en edition: le contenu de la log proc ne change pas, quand c'est en erreur
dernier selectionne, idem pour la selection dans l'arbre
(avec correction SchemaItem 1.8)
lie au clearAndSelect dans SchemaItem::select (correction SchemaItem 1.8)
-- selection rubrique containers ou types: précédente selection reste dans canvas et edition
-- destruction component instance : mal repercuté (arbres, map proc...)
-- caractères accentues dans script python d'un noeud python, fichier xml mal chargé
+- selection rubrique containers ou types: précédente selection reste dans canvas et edition
+- destruction component instance : mal repercuté (arbres, map proc...)
+- caractères accentues dans script python d'un noeud python, fichier xml mal chargé
- fermeture vue SALOME, object Browser pas mis a jour mais schema detruit...
- noeud elementaire
-----------------
- - developpé, edition : entete + ports avec nom (valeurs = tooltip ou panneau)
+ - developpé, edition : entete + ports avec nom (valeurs = tooltip ou panneau)
- reduit, edition : entete + ports sans nom
- collapsed, edition : entete seul (que les control link ?)
memes vues en execution (faut il des valeurs sur les ports ?)
-- noeud composé
+- noeud composé
-------------
- - developpé, edition : tout les internes de premier niveau visibles,
+ - developpé, edition : tout les internes de premier niveau visibles,
au moins sous forme reduite
- - macro noeud, edition : un seul macro noeud, presentation du noeud élémentaire developpé
- certains ports internes cachés
- (enrichir description IHM avec notion port privé ? )
- - reduit, edition : un seul macro noeud, presentation du noeud élémentaire réduit
- - collapsed, édition : entete seul
+ - macro noeud, edition : un seul macro noeud, presentation du noeud élémentaire developpé
+ certains ports internes cachés
+ (enrichir description IHM avec notion port privé ? )
+ - reduit, edition : un seul macro noeud, presentation du noeud élémentaire réduit
+ - collapsed, édition : entete seul
memes vues en execution
on peut ajouter 2 methodes dans le DataFlowPort :
recup valeur : string fetch()
chargement valeur : void load(string)
-à dériver dans les ports any, python, corba
+à dériver dans les ports any, python, corba
# additional include directories
INCLUDE_DIRECTORIES(
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${LIBXML2_INCLUDE_DIR}
${PYTHON_INCLUDE_DIR}
${PROJECT_SOURCE_DIR}/src/bases
void Subject::update(GuiEvent event,int type, Subject* son)
{
- //DEBTRACE("Subject::update " << type << "," << GuiObserver::eventName(event) << "," << son);
+ std::cerr << "Subject::update " << type << "," << GuiObserver::eventName(event) << "," << son << std::endl;
set<GuiObserver*> copySet = _setObs;
for (set<GuiObserver *>::iterator it = copySet.begin(); it != copySet.end(); ++it)
{
- //DEBTRACE("Subject::update " << *it);
+ std::cerr << "Subject::update " << *it << std::endl;
try
{
(*it)->update(event, type, son);
catch(Exception& ex)
{
std::cerr << "Internal error in Subject::update: " << ex.what() << std::endl;
+ std::cerr << "ERREUR ICI" << std::endl;
}
- catch(...)
- {
- std::cerr << "Internal error in Subject::update: " << std::endl;
- }
+ //catch(...)
+ // {
+ // std::cerr << "Internal error in Subject::update: " << std::endl;
+ // std::cerr << "ERREUR OU LA " << std::endl;
+ // }
}
}
INCLUDE_DIRECTORIES(
${PYTHON_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${SALOME_INCL_PATH}
${PROJECT_SOURCE_DIR}/src/bases
${PROJECT_SOURCE_DIR}/src/engine
{
CPPUNIT_FAIL(e.what());
}
+ catch(std::exception& e)
+ {
+ CPPUNIT_FAIL(e.what());
+ }
catch(...)
{
CPPUNIT_FAIL("Unknown exception");
std::cerr << "===============================================" << std::endl;
CPPUNIT_ASSERT(what.find(error_message) != std::string::npos);
}
+ catch(std::exception& e)
+ {
+ CPPUNIT_FAIL(e.what());
+ }
}
static
std::cerr << "===============================================" << std::endl;
CPPUNIT_ASSERT(what.find(error_message) != std::string::npos);
}
+ catch(std::exception& e)
+ {
+ CPPUNIT_FAIL(e.what());
+ }
}
void Py2yacsTest::t1()
void Py2yacsTest::t3()
{
const char * code_py = "def f1(a, b, c):\n"
- " print a\n"
- " print b\n"
- " print c\n";
+ " print(a)\n"
+ " print(b)\n"
+ " print(c)\n";
const char* input_ports[] = {"a", "b", "c"};
const char** output_ports;
verifyCorrectPycode(code_py, "f1", 3, input_ports, 0, output_ports);
void Py2yacsTest::t4()
{
const char * code_py = "def f1():\n"
- " print 'toto'\n"
+ " print('toto')\n"
" return\n";
const char* input_ports[] = {"a", "b", "c"};
const char** output_ports;
const char * code_py = "def f(a):\n"
" return a\n"
"if __name__ == '__main__':"
- " print 'toto'\n";
+ " print('toto')\n";
verifyWrongPycode(code_py, "f", "not accepted statement");
}
{
const char * code_py = "bla bla bla\n"
" return f1(x)\n";
- verifyWrongPycode(code_py, "f2", "SyntaxError");
+ verifyWrongPycode(code_py, "f2", "invalid syntax");
}
void Py2yacsTest::badFunctionName()
// Test the behaviour when there is an error in the python parser
void Py2yacsTest::parserErrors()
{
- verifyWrongParser("bad_parsers", "p1", "argument");
- verifyWrongParser("bad_parsers", "p2", "Attribute 'name' not found");
+ verifyWrongParser("bad_parsers", "p1", "0 positional arguments");
+ verifyWrongParser("bad_parsers", "p2", "'str' object has no attribute 'name'");
verifyWrongParser("bad_parsers", "p3", "should be a python list");
- verifyWrongParser("bad_parsers", "p4", "Traceback");
+ verifyWrongParser("bad_parsers", "p4", "unsupported operand type");
verifyWrongParser("bad_parsers", "f", "Cannot find the parsing function");
verifyWrongParser("err_py2yacs_invalid", "get_properties", "invalid syntax");
verifyWrongParser("no_file", "f", "Failed to load");
- verifyWrongParser("bad_parsers", "p5", " ");
- verifyWrongParser("bad_parsers", "p6", " ");
- verifyWrongParser("bad_parsers", "p7", " ");
+ verifyWrongParser("bad_parsers", "p5", "is not a string");
+ verifyWrongParser("bad_parsers", "p6", "is not a string");
+ verifyWrongParser("bad_parsers", "p7", "is not a string");
verifyWrongParser("bad_parsers", "p8", "Attribute 'name' should be a string.");
- verifyWrongParser("bad_parsers", "p9", " ");
- verifyWrongParser("bad_parsers", "p10", " ");
+ verifyWrongParser("bad_parsers", "p9", "Not a python list");
+ verifyWrongParser("bad_parsers", "p10", "is not a string");
}
void Py2yacsTest::globalVerification()
std::cerr << "-----------------------------------------" << std::endl;
}
-}
\ No newline at end of file
+}
static
std::string copyList(PyObject *pyList, std::list<std::string>& cppList)
{
- std::string error;
+ std::string error="";
if(!PyList_Check(pyList))
{
error = "Not a python list.\n";
}
else
{
- int n = PyList_Size(pyList);
- for(int i=0; i<n; i++)
+ Py_ssize_t n = PyList_Size(pyList);
+ for(Py_ssize_t i=0; i<n; i++)
{
PyObject *elem = PyList_GetItem(pyList,i);
- if(!PyString_Check(elem))
+ if(!PyUnicode_Check(elem))
{
std::stringstream message;
message << "List element number " << i << " is not a string.\n";
}
else
{
- const char * portName = PyString_AsString(elem);
- cppList.push_back(portName);
+ cppList.push_back(std::string(PyUnicode_AsUTF8(elem)));
}
}
}
PyObject *pystr, *module_name, *pyth_module, *pyth_func;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
pystr = PyObject_Str(pvalue);
- result = PyString_AsString(pystr);
+ result = std::string(PyUnicode_AsUTF8(pystr));
result += "\n";
Py_DECREF(pystr);
/* See if we can get a full traceback */
if(ptraceback)
{
- module_name = PyString_FromString("traceback");
+ module_name = PyUnicode_FromString("traceback");
pyth_module = PyImport_Import(module_name);
Py_DECREF(module_name);
if (pyth_module)
for(int i=0; i<n; i++)
{
pystr = PyList_GetItem(pyList,i);
- result += PyString_AsString(pystr);
+ result += std::string(PyUnicode_AsUTF8(pystr));
}
Py_DECREF(pyList);
}
// Py_Initialize();
YACS::ENGINE::AutoGIL agil;
- pValue = PyString_FromString(_python_parser_module.c_str());
+ pValue = PyUnicode_FromString(_python_parser_module.c_str());
pModule = PyImport_Import(pValue);
Py_DECREF(pValue);
if (pFunc && PyCallable_Check(pFunc))
{
pArgs = PyTuple_New(1);
- pValue = PyString_FromString(python_code.c_str());
+ pValue = PyUnicode_FromString(python_code.c_str());
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyObject_CallObject(pFunc, pArgs);
{
errorMessage += "Parsing function should return a tuple of two string lists.\n";
}
- int n = PyTuple_Size(pValue);
+ Py_ssize_t n = PyTuple_Size(pValue);
if(n != 2)
{
errorMessage += "Parsing function should return two string lists.\n";
if(pAttribute = checkAndGetAttribute(fpy, "name", errorMessage))
{
- if(!PyString_Check(pAttribute))
+ if(!PyUnicode_Check(pAttribute))
{
errorMessage += "Attribute 'name' should be a string.\n";
Py_DECREF(pAttribute);
{
_functions.push_back(FunctionProperties());
FunctionProperties& fcpp = _functions.back();
- fcpp._name=PyString_AsString(pAttribute);
+ fcpp._name=std::string(PyUnicode_AsUTF8(pAttribute));
Py_DECREF(pAttribute);
if(pAttribute = checkAndGetAttribute(fpy, "inputs", errorMessage))
class v(ast.NodeVisitor):
def visit_Module(self, node):
- #print type(node).__name__, ":"
+ #print(type(node).__name__, ":")
accepted_tokens = ["Import", "ImportFrom", "FunctionDef", "ClassDef"]
#print "module body:"
self.global_errors=[]
error="py2yacs error at line %s: not accepted statement '%s'." % (
e.lineno, type_name)
self.global_errors.append(error)
- #print type_name
- #print "------------------------------------------------------------------"
+ #print(type_name)
+ #print("------------------------------------------------------------------")
self.functions=[]
self.lastfn=""
self.infunc=False
self.generic_visit(node)
pass
def visit_FunctionDef(self, node):
- #print type(node).__name__, ":", node.name
+ #print(type(node).__name__, ":", node.name)
if not self.infunc:
self.lastfn = FunctionProperties(node.name)
self.functions.append(self.lastfn)
self.lastfn = None
self.infunc=False
pass
- def visit_arguments(self, node):
- #print type(node).__name__, ":"
- self.inargs=True
- self.generic_visit(node)
- self.inargs=False
- pass
- def visit_Name(self, node):
- if self.inargs :
- #print type(node).__name__, ":", node.id
- self.lastname=node.id
- self.generic_visit(node)
- pass
- def visit_Param(self, node):
- #print type(node).__name__, ":", self.lastname
- self.lastfn.inputs.append(self.lastname)
+ def visit_arg(self, node):
+ #print(type(node).__name__, ":", node.arg)
+ self.lastfn.inputs.append(node.arg)
pass
def visit_Return(self, node):
- #print type(node).__name__, ":", node.value
+ #print(type(node).__name__, ":", node.value)
if self.lastfn.outputs is not None :
error="py2yacs error at line %s: multiple returns." % node.lineno
self.lastfn.errors.append(error)
fn_name = args.def_name
functions,errors = get_properties(text_file)
- print "global errors:", errors
+ print("global errors:", errors)
for f in functions:
- print f
+ print(f)
fn_properties = next((f for f in functions if f.name == fn_name), None)
if fn_properties is not None :
fn_properties.inputs, fn_properties.outputs,
args.output)
else:
- print "\n".join(fn_properties.errors)
+ print("\n".join(fn_properties.errors))
else:
- print "Function not found:", fn_name
-
\ No newline at end of file
+ print("Function not found:", fn_name)
"""
import sys,os
from qt import *
-import Tree
-import PanelManager
-import BoxManager
-import Icons
-import Items
-import adapt
-import Item
-import logview
+from . import Tree
+from . import PanelManager
+from . import BoxManager
+from . import Icons
+from . import Items
+from . import adapt
+from . import Item
+from . import logview
import pilot
import threading
import time
-import CONNECTOR
-import catalog
+from . import CONNECTOR
+from . import catalog
import traceback
import glob
def run(self):
try:
self.executor.RunW(self.proc,0)
- except ValueError,ex:
+ except ValueError as ex:
#traceback.print_exc()
QApplication.postEvent(self.parent, ErrorEvent('YACS execution error',str(ex)))
if __name__ == "__main__":
- from Item import Item
+ from .Item import Item
app = QApplication(sys.argv)
t=Appli()
t.objectBrowser.additem(Item("item1"))
#
from qt import *
-import CONNECTOR
+from . import CONNECTOR
class BoxManager(QWidgetStack):
""" A BoxManager manages a collection of widget
CONNECTOR.Connect(self.rootItem,"selected",self.setview,())
def setview(self,item):
- if not self.panels.has_key(item):
+ if item not in self.panels:
CONNECTOR.Connect(item,"changed",self.changePanel,(item,))
panel=item.box(self)
self.panels[item]=panel
self.raiseWidget(self.panels[item])
def changePanel(self,item):
- print "changePanel",item
- if self.panels.has_key(item):
+ print("changePanel",item)
+ if item in self.panels:
self.removeWidget(self.panels[item])
panel=item.box(self)
self.panels[item]=panel
from qtcanvas import *
import pilot
import pypilot
-import Item
+from . import Item
import math
dispatcher=pilot.Dispatcher.getDispatcher()
return menu
def delete(self):
- print "delete link"
+ print("delete link")
def tooltip(self,view,pos):
r = QRect(pos.x(), pos.y(), pos.x()+10, pos.y()+10)
return menu
def connect(self):
- print "ControlItem.connect",self.context
- print self.port
+ print("ControlItem.connect",self.context)
+ print(self.port)
item=Item.adapt(self.port)
- print item
+ print(item)
item.connect()
self.context.connecting(item)
#self.context.connecting(self)
#Protocol to link 2 objects (ports, at first)
#First, notify the canvas View (or any view that can select) we are connecting (see method connect above)
#Second (and last) make the link in the link method of object that was declared connecting
- print "link:",obj
+ print("link:",obj)
def tooltip(self,view,pos):
r = QRect(pos.x(), pos.y(), self.width(), self.height())
def link(self,obj):
#Here we create the link between self and obj.
#self has been declared connecting in connect method
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,OutControlItem):
#Connection possible
l=LinkItem(obj,self,self.canvas())
def link(self,obj):
#Here we create the link between self and obj.
#self has been declared connecting in connect method
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,InControlItem):
#Connection possible
l=LinkItem(self,obj,self.canvas())
return menu
def connect(self):
- print "PortItem.connect",self.context
- print self.port
+ print("PortItem.connect",self.context)
+ print(self.port)
item=Item.adapt(self.port)
- print item
+ print(item)
self.context.connecting(item)
#self.context.connecting(self)
def link(self,obj):
- print "PortItem.link:",obj
+ print("PortItem.link:",obj)
def tooltip(self,view,pos):
r = QRect(pos.x(),pos.y(),self.width(), self.height())
def link(self,obj):
#Here we create the link between self and obj.
#self has been declared connecting in connect method
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,OutPortItem):
#Connection possible
l=LinkItem(obj,self,self.canvas())
def link(self,obj):
#Here we create the link between self and obj.
#self has been declared connecting in connect method
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,InPortItem):
#Connection possible
l=LinkItem(self,obj,self.canvas())
color= self.colors.get(color,Qt.white)
self.setBrush(QBrush(color))
else:
- print "Unknown custom event type:", event.type()
+ print("Unknown custom event type:", event.type())
def moveBy(self,dx,dy):
QCanvasRectangle.moveBy(self,dx,dy)
#QToolTip(view).tip( r, s )
def browse(self):
- print "browse"
+ print("browse")
def selected(self):
"""The canvas item has been selected"""
# -*- coding: iso-8859-15 -*-
#
"""
- La classe CONNECTOR sert à enregistrer les observateurs d'objets et à délivrer
- les messages émis à ces objets.
+ La classe CONNECTOR sert à enregistrer les observateurs d'objets et à délivrer
+ les messages émis à ces objets.
- Le principe général est le suivant : un objet (subscriber) s'enregistre aupres du
+ Le principe général est le suivant : un objet (subscriber) s'enregistre aupres du
connecteur global (theconnector) pour observer un objet emetteur de messages (publisher)
- sur un canal donné (channel). Il demande à etre notifie par appel d'une fonction (listener).
- La séquence est donc :
+ sur un canal donné (channel). Il demande à etre notifie par appel d'une fonction (listener).
+ La séquence est donc :
- enregistrement du subscriber pour le publisher : theconnector.Connect(publisher,channel,listener,args)
- - émission du message par le publisher : theconnector.Emit(publisher,channel,cargs)
+ - émission du message par le publisher : theconnector.Emit(publisher,channel,cargs)
- args et cargs sont des tuples contenant les arguments de la fonction listener qui sera appelée
+ args et cargs sont des tuples contenant les arguments de la fonction listener qui sera appelée
comme suit::
listener(cargs+args)
def Connect(self, object, channel, function, args):
###print "Connect",object, channel, function, args
idx = id(object)
- if self.connections.has_key(idx):
+ if idx in self.connections:
channels = self.connections[idx]
else:
channels = self.connections[idx] = {}
- if channels.has_key(channel):
+ if channel in channels:
receivers = channels[channel]
else:
receivers = channels[channel] = []
try:
receivers = self.connections[id(object)][channel]
except KeyError:
- raise ConnectorError, \
- 'no receivers for channel %s of %s' % (channel, object)
+ raise ConnectorError('no receivers for channel %s of %s' % (channel, object))
for funct,fargs in receivers[:]:
if funct() is None:
del self.connections[id(object)]
return
- raise ConnectorError,\
- 'receiver %s%s is not connected to channel %s of %s' \
- % (function, args, channel, object)
+ raise ConnectorError('receiver %s%s is not connected to channel %s of %s' \
+ % (function, args, channel, object))
def Emit(self, object, channel, *args):
try:
func=rfunc()
if func:
- apply(func, args + fargs)
+ func(*args + fargs)
else:
# Le receveur a disparu
if (rfunc,fargs) in receivers:receivers.remove((rfunc,fargs))
class BoundMethodWeakref(object):
def __init__(self,callable):
- self.Self=weakref.ref(callable.im_self)
- self.Func=weakref.ref(callable.im_func)
+ self.Self=weakref.ref(callable.__self__)
+ self.Func=weakref.ref(callable.__func__)
def __call__(self):
target=self.Self()
class A:pass
class B:
def add(self,a):
- print "add",self,a
+ print("add",self,a)
def __del__(self):
- print "__del__",self
+ print("__del__",self)
def f(a):
- print f,a
- print "a=A()"
+ print(f,a)
+ print("a=A()")
a=A()
- print "b=B()"
+ print("b=B()")
b=B()
- print "c=B()"
+ print("c=B()")
c=B()
Connect(a,"add",b.add,())
Connect(a,"add",b.add,())
Connect(a,"add",c.add,())
Connect(a,"add",f,())
Emit(a,"add",1)
- print "del b"
+ print("del b")
del b
Emit(a,"add",1)
- print "del f"
+ print("del f")
del f
Emit(a,"add",1)
Disconnect(a,"add",c.add,())
#self.canvas().update()
def addNode(self):
- print "addNode"
+ print("addNode")
def zoomIn(self):
m = self.worldMatrix()
def connecting(self,obj):
"""Method called by an item to notify canvasView a connection has begun"""
- print "connecting",obj
+ print("connecting",obj)
self.__connecting=obj
def contentsMouseMoveEvent(self,e):
return menu
def delete(self):
- print "delete link"
+ print("delete link")
def tooltip(self,view,pos):
r = QRect(pos.x(), pos.y(), pos.x()+10, pos.y()+10)
return menu
def connect(self):
- print "connect",self.context
+ print("connect",self.context)
self.context.connecting(self)
def link(self,obj):
- print "link:",obj
+ print("link:",obj)
def tooltip(self,view,pos):
r = QRect(self.x(), self.y(), self.width(), self.height())
link.setToPoint( int(self.x()), int(self.y()) )
def link(self,obj):
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,OutPortItem):
#Connection possible
l=LinkItem(obj,self,self.canvas())
link.setFromPoint( int(self.x()), int(self.y()) )
def link(self,obj):
- print "link:",obj
+ print("link:",obj)
if isinstance(obj,InPortItem):
#Connection possible
l=LinkItem(self,obj,self.canvas())
view.tip( r, s )
def browse(self):
- print "browse"
+ print("browse")
def selected(self):
- print "selected"
+ print("selected")
if __name__=='__main__':
app=QApplication(sys.argv)
import os
from qt import QPixmap
-from imagesxpm import dico_xpm
+from .imagesxpm import dico_xpm
dico_images={}
def get_image(name):
- if dico_images.has_key(name):
+ if name in dico_images:
return dico_images[name]
else :
- if dico_xpm.has_key(name):
+ if name in dico_xpm:
image=QPixmap(dico_xpm[name])
else:
fic_image = os.path.join(os.path.dirname(__file__),"icons",name)
import sys
from qt import *
-import CONNECTOR
-import adapt
+from . import CONNECTOR
+from . import adapt
class Item:
def __init__(self,label=""):
ADAPT=adapt.adapt
items={}
def adapt(obj):
- if items.has_key(obj.ptr()):
+ if obj.ptr() in items:
return items[obj.ptr()]
else:
item= ADAPT(obj,Item)
import sys
import pilot
import SALOMERuntime
-import Item
-import adapt
+from . import Item
+from . import adapt
from qt import *
from qtcanvas import *
-import Editor
-import CItems
+from . import Editor
+from . import CItems
import pygraphviz
import traceback
-import CONNECTOR
-import graph
-import panels
+from . import CONNECTOR
+from . import graph
+from . import panels
class DataLinkItem(Item.Item):
def __init__(self,pin,pout):
return tabWidget
def addNode(self,service):
- print "Composed.addNode",service
+ print("Composed.addNode",service)
#add node service in the parent self which is a ComposedNode
new_node=service.clone(None)
ItemComposedNode.n=ItemComposedNode.n+1
panels=[("Panel1",panel1)]
def addLink(self,link):
- print "Composed.addLink",link
+ print("Composed.addLink",link)
if isinstance(link,DataLinkItem):
self.datalinks.addLink(link)
elif isinstance(link,StreamLinkItem):
class ItemProc(ItemComposedNode):
"""Item pour la procedure"""
def connecting(self,item):
- print "ItemProc.connecting",item
+ print("ItemProc.connecting",item)
self._connecting=item
class ItemPort(Item.Item):
box=panel
def link(self,other):
- print "ItemPort.link:",self,other
+ print("ItemPort.link:",self,other)
def connect(self):
- print "ItemPort.connect:"
+ print("ItemPort.connect:")
self.root.connecting(self)
class ItemInPort(ItemPort):
if not cflink:
#add also a control flow link
fitem.addLink(ControlLinkItem(nodeS,nodeE))
- except ValueError,ex:
+ except ValueError as ex:
traceback.print_exc()
QMessageBox.warning(None,"YACS error",str(ex))
return
l=StreamLinkItem(other.port,self.port)
fitem=Item.adapt(father)
fitem.addLink(l)
- except ValueError,ex:
+ except ValueError as ex:
traceback.print_exc()
QMessageBox.warning(None,"YACS error",str(ex))
return
#
from qt import *
-import CONNECTOR
+from . import CONNECTOR
class PanelManager(QWidgetStack):
""" A PanelManager manages a collection of widget
CONNECTOR.Connect(self.rootItem,"dblselected",self.setview,())
def setview(self,item):
- if not self.panels.has_key(item):
+ if item not in self.panels:
panel=item.panel(self)
self.panels[item]=panel
idd=self.addWidget(panel)
# -*- coding: iso-8859-15 -*-
#
-"""Ce module permet de créer des vues sous forme d'arbre
- Ces vues sont construites à partir des informations
- fournies par un modèle
+"""Ce module permet de créer des vues sous forme d'arbre
+ Ces vues sont construites à partir des informations
+ fournies par un modèle
"""
import sys
from qt import *
-import Icons
-import CONNECTOR
+from . import Icons
+from . import CONNECTOR
class Tree(QListView):
"""Tree(parent=None)
if __name__ == "__main__":
- from Item import Item
+ from .Item import Item
app = QApplication(sys.argv)
t=Tree()
t.additem(Item("item1"))
else:
adapter = factory(obj, protocol, alternate)
if adapter is AdaptationError:
- raise AdaptationError,obj
+ raise AdaptationError(obj)
else:
return adapter
#
from qt import *
-import Tree
-from BoxManager import BoxManager
+from . import Tree
+from .BoxManager import BoxManager
class Browser(QVBox):
def __init__(self,parent,appli):
#
from qt import *
-import browser
-import cataitems
+from . import browser
+from . import cataitems
class Browser(browser.Browser):
def init(self):
self.connect( but1, SIGNAL("clicked()"), self.handleBut1 )
def handleBut1(self):
- print "handleBut1",self.selected
+ print("handleBut1",self.selected)
if hasattr(self.selected,"addNode"):
self.selected.addNode(self.appli)
return
import sys
from qt import *
-import browser
-import sessions
+from . import browser
+from . import sessions
import pilot
class Browser(browser.Browser):
from qt import *
-import Item
-import CONNECTOR
-import Items
+from . import Item
+from . import CONNECTOR
+from . import Items
class Obj(Item.Item):
def __init__(self,root=None):
def getChildren(self):
sublist=[]
- for service in self.compo._serviceMap.values():
+ for service in list(self.compo._serviceMap.values()):
itemservice=ItemService(service,self.root)
sublist.append(itemservice)
return sublist
def getChildren(self):
sublist=[]
- for name,typ in self.typeMap.items():
+ for name,typ in list(self.typeMap.items()):
itemtype=ItemType(typ,self.root,name)
sublist.append(itemtype)
return sublist
def getChildren(self):
sublist=[]
- for compo in self.compoMap.values():
+ for compo in list(self.compoMap.values()):
itemcompo=ItemCompo(compo,self.root)
sublist.append(itemcompo)
return sublist
def getChildren(self):
sublist=[]
- for node in self.nodesMap.values():
+ for node in list(self.nodesMap.values()):
itemnode=ItemNode(node,self.root)
sublist.append(itemnode)
return sublist
def getChildren(self):
sublist=[]
- for node in self.composedMap.values():
+ for node in list(self.composedMap.values()):
itemnode=ItemComposedNode(node,self.root)
sublist.append(itemnode)
return sublist
#
from qt import *
-import browser_session
-import browser_catalog
+from . import browser_session
+from . import browser_catalog
import pilot
class CatalogTool(QMainWindow):
return
filename = str(fn)
cata=pilot.getRuntime().loadCatalog("proc",filename)
- print cata
- print cata._nodeMap
- for name,node in cata._nodeMap.items():
- print name,node
+ print(cata)
+ print(cata._nodeMap)
+ for name,node in list(cata._nodeMap.items()):
+ print(name,node)
self.register(cata,filename)
def register(self,cata,name):
import sys
import pilot
-import Item
+from . import Item
from qt import *
from qtcanvas import *
-from GraphViewer import GraphViewer
-import Editor
-import CItems
+from .GraphViewer import GraphViewer
+from . import Editor
+from . import CItems
import pygraphviz
from pygraphviz import graphviz as gv
import traceback
-import CONNECTOR
+from . import CONNECTOR
import bisect
class MyCanvas(QCanvas):
citems[n.ptr()]=c
c.show()
- for k,n in citems.items():
+ for k,n in list(citems.items()):
for p in n.inports:
pitems[p.port.ptr()]=p
for p in n.outports:
self.layout("LR")
def addLink(self,link):
- print "graph.addLink",link
+ print("graph.addLink",link)
#CItem for outport
nodeS=self.citems[link.pout.getNode().ptr()]
nodeE=self.citems[link.pin.getNode().ptr()]
G.graph_attr["dpi"]="72"
dpi=72.
aspect=dpi/72
- for k,n in self.citems.items():
+ for k,n in list(self.citems.items()):
#k is node address (YACS)
#n is item in canvas
G.add_node(k)
continue
G.add_edge(pout.getNode().ptr(),pin.getNode().ptr())
- for k,n in self.citems.items():
+ for k,n in list(self.citems.items()):
for ndown in n.node.getOutNodes():
G.add_edge(n.node.ptr(),ndown.ptr())
self.canvas.update()
def clearLinks(self):
- items=self.citems.values()
+ items=list(self.citems.values())
for node in items:
for port in node.outports:
if not hasattr(port,"links"):
self.canvas.update()
def orthoLinks(self):
- items=self.citems.values()
+ items=list(self.citems.values())
g=grid(items)
for node in items:
for port in node.outports:
self.xs=xs
self.ys=ys
self.cols=[]
- for w in xrange(len(xs)-1):
+ for w in range(len(xs)-1):
col=[]
x=(xs[w]+xs[w+1])/2
- for h in xrange(len(ys)-1):
+ for h in range(len(ys)-1):
y=(ys[h]+ys[h+1])/2
col.append(node((x,y),(w,h)))
self.cols.append(col)
self.open.append((fromNode.total,fromNode))
toNode=self.get(toLoc)
if toNode.blocked:
- print "toNode is blocked"
+ print("toNode is blocked")
return []
destx,desty=toNode.coord
while self.open:
from qt import *
import traceback
-import Editor
-import Item
+from . import Editor
+from . import Item
class PanelScript(QVBox):
def __init__(self,parent,item):
from omniORB import CORBA
import CosNaming
-import Item
-import CONNECTOR
+from . import Item
+from . import CONNECTOR
class Sessions(Item.Item):
def __init__(self,port):
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print "p1:",p1</code>
+ <code> print("p1:",p1)</code>
<code><![CDATA[ condition=p1 < 40.]]> </code>
<code> return p1,condition</code>
</function>
INCLUDE_DIRECTORIES(
${OMNIORB_INCLUDE_DIR}
${OMNIORB_ROOT_DIR}/include/omniORB4/internal
+ ${OMNIORBPY_INCLUDE_DIR}
${SALOME_INCL_PATH}
${PROJECT_SOURCE_DIR}/src/bases
${PROJECT_SOURCE_DIR}/src/engine
std::string InputCorbaPort::valToStr()
{
- int isString = PyString_Check(getPyObj());
+ int isString = PyBytes_Check(getPyObj());
PyObject *strPyObj = PyObject_Str(getPyObj());
- string val = PyString_AsString(strPyObj);
+ string val = PyBytes_AsString(strPyObj);
if (isString)
val = "\"" + val + "\"";
Py_DECREF(strPyObj);
std::string OutputCorbaPort::valToStr()
{
PyObject *strPyObj = PyObject_Str(getPyObj());
- string val = PyString_AsString(strPyObj);
+ string val = PyBytes_AsString(strPyObj);
Py_DECREF(strPyObj);
return val;
}
_errorDetails=msg.str();
throw Exception(msg.str());
}
- const char picklizeScript[]="import cPickle\ndef pickleForDistPyth2009(*args,**kws):\n return cPickle.dumps((args,kws),-1)\n\ndef unPickleForDistPyth2009(st):\n args=cPickle.loads(st)\n return args\n";
+ const char picklizeScript[]="import pickle\ndef pickleForDistPyth2009(*args,**kws):\n return pickle.dumps((args,kws),-1)\n\ndef unPickleForDistPyth2009(st):\n args=pickle.loads(st)\n return args\n";
PyObject *res=PyRun_String(picklizeScript,Py_file_input,_context,_context);
if(res == NULL)
{
PyTuple_SetItem(args,pos,ob);
}
PyObject *serializationInput=PyObject_CallObject(_pyfuncSer,args);
- std::string serializationInputC=PyString_AsString(serializationInput);
+ std::string serializationInputC=PyBytes_AsString(serializationInput);
serializationInputCorba=new Engines::pickledArgs;
int len=serializationInputC.length();
serializationInputCorba->length(serializationInputC.length());
{
AutoGIL agil;
args = PyTuple_New(1);
- PyObject* resultPython=PyString_FromString(resultCorbaC);
+ PyObject* resultPython=PyBytes_FromString(resultCorbaC);
delete [] resultCorbaC;
PyTuple_SetItem(args,0,resultPython);
PyObject *finalResult=PyObject_CallObject(_pyfuncUnser,args);
{
OutputPyPort *p=(OutputPyPort *)*iter;
DEBTRACE( "port name: " << p->getName() );
- DEBTRACE( "port kind: " << p->edGetType()->kind() );
+ DEBTRACE( "port kind: " << p->typeName() );
DEBTRACE( "port pos : " << pos );
if(PyTuple_Check(finalResult))ob=PyTuple_GetItem(finalResult,pos) ;
else ob=finalResult;
static PyTypeObject PyStdOut_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "PyOut", /*tp_name*/
- sizeof(PyStdOut), /*tp_basicsize*/
- 0, /*tp_itemsize*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /*0,*/ /*ob_size*/
+ "PyOut", /*tp_name*/
+ sizeof(PyStdOut), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
/* methods */
(destructor)PyStdOut_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- PyObject_GenericGetAttr, /*tp_getattro*/
- /* softspace is writable: we must supply tp_setattro */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- PyStdOut_methods, /*tp_methods*/
- PyStdOut_memberlist, /*tp_members*/
- 0, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- 0, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ PyObject_GenericGetAttr, /*tp_getattro*/
+ /* softspace is writable: we must supply tp_setattro */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ PyStdOut_methods, /*tp_methods*/
+ PyStdOut_memberlist, /*tp_members*/
+ 0, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ 0, /*tp_init*/
+ 0, /*tp_alloc*/
+ 0, /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
std::ostringstream oss; oss << "evalPy failed : " << errorDetails;
throw Exception(oss.str());
}
- AutoPyRef res(PyEval_EvalCode(reinterpret_cast<PyCodeObject *>((PyObject *)code),context,context));
+ AutoPyRef res(PyEval_EvalCode((PyObject *)code,context,context));
PyObject *ret(PyDict_GetItemString(context,funcName.c_str())); //borrowed ref
if(!ret)
throw YACS::Exception("evalPy : Error on returned func !");
using namespace YACS::ENGINE;
using namespace std;
-const char PythonEntry::SCRIPT_FOR_SIMPLE_SERIALIZATION[]="import cPickle\n"
+const char PythonEntry::SCRIPT_FOR_SIMPLE_SERIALIZATION[]="import pickle\n"
"def pickleForVarSimplePyth2009(val):\n"
- " return cPickle.dumps(val,-1)\n"
+ " return pickle.dumps(val,-1)\n"
"\n";
const char PythonNode::IMPL_NAME[]="Python";
const char PythonNode::KIND[]="Python";
-const char PythonNode::SCRIPT_FOR_SERIALIZATION[]="import cPickle\n"
+const char PythonNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
"def pickleForDistPyth2009(kws):\n"
- " return cPickle.dumps(((),kws),-1)\n"
+ " return pickle.dumps(((),kws),-1)\n"
"\n"
"def unPickleForDistPyth2009(st):\n"
- " args=cPickle.loads(st)\n"
+ " args=pickle.loads(st)\n"
" return args\n";
const char PythonNode::REMOTE_NAME[]="remote";
const char PythonNode::DPL_INFO_NAME[]="my_dpl_localization";
-const char PyFuncNode::SCRIPT_FOR_SERIALIZATION[]="import cPickle\n"
+const char PyFuncNode::SCRIPT_FOR_SERIALIZATION[]="import pickle\n"
"def pickleForDistPyth2009(*args,**kws):\n"
- " return cPickle.dumps((args,kws),-1)\n"
+ " return pickle.dumps((args,kws),-1)\n"
"\n"
"def unPickleForDistPyth2009(st):\n"
- " args=cPickle.loads(st)\n"
+ " args=pickle.loads(st)\n"
" return args\n";
//The pickled string may contain NULL characters so use PyString_AsStringAndSize
char *serializationInputC(0);
Py_ssize_t len;
- if (PyString_AsStringAndSize(serializationInput, &serializationInputC, &len))
+ if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
throw Exception("DistributedPythonNode problem in python pickle");
serializationInputCorba->length(len);
for(int i=0; i < len ; i++)
{
AutoGIL agil;
PyObject *args(0),*ob(0);
- PyObject* resultPython=PyString_FromStringAndSize(resultCorbaC,resultCorba->length());
+ PyObject* resultPython=PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length());
delete [] resultCorbaC;
args = PyTuple_New(1);
PyTuple_SetItem(args,0,resultPython);
PyObject* code=Py_CompileString(_script.c_str(), stream.str().c_str(), Py_file_input);
if(code == NULL)
{
- _errorDetails="";
+ _errorDetails="";
PyObject* new_stderr = newPyStdOut(_errorDetails);
PySys_SetObject((char*)"stderr", new_stderr);
PyErr_Print();
Py_DECREF(new_stderr);
throw Exception("Error during execution");
}
- PyObject *res = PyEval_EvalCode((PyCodeObject *)code, _context, _context);
+ PyObject *res = PyEval_EvalCode( code, _context, _context);
Py_DECREF(code);
Py_XDECREF(res);
{
const std::pair<std::string,int>& p(ret[i]);
PyObject *elt(PyTuple_New(2));
- PyTuple_SetItem(elt,0,PyString_FromString(p.first.c_str()));
+ PyTuple_SetItem(elt,0,PyBytes_FromString(p.first.c_str()));
PyTuple_SetItem(elt,1,PyLong_FromLong(p.second));
PyList_SetItem(ob,i,elt);
}
Py_XDECREF(ob);
char *serializationInputC(0);
Py_ssize_t len;
- if (PyString_AsStringAndSize(serializationInput, &serializationInputC, &len))
+ if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
throw Exception("DistributedPythonNode problem in python pickle");
serializationInputCorba->length(len);
for(int i=0; i < len ; i++)
Py_DECREF(new_stderr);
throw Exception("Error during execution");
}
- PyObject *res = PyEval_EvalCode((PyCodeObject *)code, _context, _context);
+ PyObject *res = PyEval_EvalCode( code, _context, _context);
Py_DECREF(code);
Py_XDECREF(res);
//The pickled string may contain NULL characters so use PyString_AsStringAndSize
char *serializationInputC(0);
Py_ssize_t len;
- if (PyString_AsStringAndSize(serializationInput, &serializationInputC, &len))
+ if (PyBytes_AsStringAndSize(serializationInput, &serializationInputC, &len))
throw Exception("DistributedPythonNode problem in python pickle");
serializationInputCorba->length(len);
{
AutoGIL agil;
- PyObject *resultPython(PyString_FromStringAndSize(resultCorbaC,resultCorba->length()));
+ PyObject *resultPython(PyBytes_FromStringAndSize(resultCorbaC,resultCorba->length()));
delete [] resultCorbaC;
PyObject *args(PyTuple_New(1)),*ob(0);
PyTuple_SetItem(args,0,resultPython);
if (PyObject_HasAttrString(data, (char*)"_is_a"))
{
PyObject *result = PyObject_CallMethod(data, (char*)"_is_a", (char*)"s",(char*)"IDL:SALOME/GenericObj:1.0");
- if(result && PyInt_Check(result))
+ if(result && PyLong_Check(result))
{
- if(PyInt_AS_LONG(result))
+ if(PyLong_AS_LONG(result))
{
PyObject* o=PyObject_CallMethod(data, (char*)"Destroy", (char*)"");
if(o)
if (PyObject_HasAttrString(data, (char*)"_is_a"))
{
PyObject *result = PyObject_CallMethod(data, (char*)"_is_a", (char*)"s",(char*)"IDL:SALOME/GenericObj:1.0");
- if(result && PyInt_Check(result))
+ if(result && PyLong_Check(result))
{
- if(PyInt_AS_LONG(result))
+ if(PyLong_AS_LONG(result))
{
PyObject* o= PyObject_CallMethod(data, (char*)"Register", (char*)"") ;
if(o)
if(!ret)
return dump();
std::string retCpp;
- char *val(PyString_AsString(ret));
+ char *val(PyBytes_AsString(ret));
if(val)
retCpp=val;
Py_XDECREF(ret);
std::string InputPyPort::valToStr()
{
- int isString = PyString_Check(getPyObj());
+ int isString = PyBytes_Check(getPyObj());
//DEBTRACE("isString=" << isString);
PyObject *strPyObj = PyObject_Str(getPyObj());
//DEBTRACE(PyString_Size(strPyObj));
- string val = PyString_AsString(strPyObj);
+ string val = PyBytes_AsString(strPyObj);
if (isString)
val = "\"" + val + "\"";
//DEBTRACE(val);
std::string OutputPyPort::valToStr()
{
PyObject *strPyObj = PyObject_Str(getPyObj());
- string val = PyString_AsString(strPyObj);
+ string val = PyBytes_AsString(strPyObj);
Py_DECREF(strPyObj);
return val;
}
Py_InitializeEx(0); // do not install signal handlers
#endif
if (argc > 0 && argv != NULL)
- PySys_SetArgv(argc, argv);
+ {
+ wchar_t **changed_argv = new wchar_t*[argc];
+ for (int i = 0; i < argc; i++)
+ {
+ changed_argv[i] = Py_DecodeLocale(argv[i], NULL);
+ }
+ PySys_SetArgv(argc, changed_argv);
+ }
else
{
int pyArgc = 1;
char* pyArgv[1];
char defaultName[] = "SALOME_YACS_RUNTIME";
+ wchar_t **changed_pyArgv = new wchar_t*[pyArgc];
pyArgv[0] = defaultName;
- PySys_SetArgv(pyArgc, pyArgv);
+ for (int i = 0; i < pyArgc; i++)
+ {
+ changed_pyArgv[i] = Py_DecodeLocale(pyArgv[i], NULL);
+ }
+ PySys_SetArgv(pyArgc, changed_pyArgv);
}
PyEval_InitThreads(); /* Create (and acquire) the interpreter lock (for threads)*/
PyEval_SaveThread(); /* Release the thread state */
{
goto out;
}
- _api = (omniORBpyAPI*)PyCObject_AsVoidPtr(pyapi);
+ _api = (omniORBpyAPI*)PyCapsule_GetPointer(pyapi,"_omnipy.API");
Py_DECREF(pyapi);
res=PyRun_String("\n"
#include <Python.h>
#include <omniORB4/CORBA.h>
+#include <omniORBpy.h>
#include "Runtime.hxx"
#include<string>
#include<set>
-
-//--- from omniORBpy.h (not present on Debian Sarge packages)
-struct omniORBpyAPI
-{
- PyObject* (*cxxObjRefToPyObjRef)(const CORBA::Object_ptr cxx_obj,
- CORBA::Boolean hold_lock);
- // Convert a C++ object reference to a Python object reference.
- // If <hold_lock> is true, caller holds the Python interpreter lock.
-
- CORBA::Object_ptr (*pyObjRefToCxxObjRef)(PyObject* py_obj,
- CORBA::Boolean hold_lock);
- // Convert a Python object reference to a C++ object reference.
- // Raises BAD_PARAM if the Python object is not an object reference.
- // If <hold_lock> is true, caller holds the Python interpreter lock.
-
- PyObject* (*handleCxxSystemException)(const CORBA::SystemException& ex);
- // Sets the Python exception state to reflect the given C++ system
- // exception. Always returns NULL. The caller must hold the Python
- // interpreter lock.
-};
-//--- end of from omniORBpy.h (not present on Debian Sarge packages)
namespace YACS
{
bool isEmptyName;
std::string str(sct.getNotNullContainerName(cont,askingNode,isEmptyName));
- DEBTRACE("SalomeContainer::start " << str <<";"<< _sct.getHostName() <<";"<<_type);
+ DEBTRACE("SalomeContainer::start " << str <<";"<< sct.getHostName() <<";"<<shutdownLevel);
// Finalize parameters with components found in the container
if(!CORBA::is_nil(trueCont))
{
shutdownLevel=3;
- DEBTRACE( "container found: " << str << " " << _shutdownLevel );
+ DEBTRACE( "container found: " << str << " " << shutdownLevel );
}
else
{
shutdownLevel=2;
myparams.mode="start";
- DEBTRACE( "container not found: " << str << " " << _shutdownLevel);
+ DEBTRACE( "container not found: " << str << " " << shutdownLevel);
}
}
cerr << "---------------SalomePythonNode::load function---------------" << endl;
list<OutputPort *>::iterator iter;
string value2Export=((SalomePythonComponent*)_component)->getStringValueToExportInInterp(this);
- PyObject* ob=PyString_FromString(value2Export.c_str());
+ PyObject* ob=PyBytes_FromString(value2Export.c_str());
PyDict_SetItemString(_context,PLACEMENT_VAR_NAME_IN_INTERP,ob);
for(iter = _setOfOutputPort.begin(); iter != _setOfOutputPort.end(); iter++)
{
${CPPUNIT_INCLUDE_DIRS}
${PYTHON_INCLUDE_DIR}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${KERNEL_INCLUDE_DIRS}
${CMAKE_CURRENT_SOURCE_DIR}/..
${CMAKE_CURRENT_SOURCE_DIR}/../../bases
INSTALL(TARGETS echo_clt DESTINATION ${LOCAL_TEST_DIR})
INSTALL(FILES CTestTestfileInstall.cmake
DESTINATION ${LOCAL_TEST_DIR}
- RENAME CTestTestfile.cmake)
\ No newline at end of file
+ RENAME CTestTestfile.cmake)
string s = ss.str();
ElementaryNode* node = _myRuntime->createScriptNode("",s);
_nodeMap[s] = node;
- ((InlineNode*) node)->setScript("print 'node 13'\n"
+ ((InlineNode*) node)->setScript("print('node 13')\n"
"import eo\n"
- "print ob\n"
+ "print(ob)\n"
"o=ob._narrow(eo.Obj)\n"
- "print o\n"
- "print o.echoLong(13)\n"
+ "print(o)\n"
+ "print(o.echoLong(13))\n"
"a=dble+1\n"
"dble=2*a\n"
- "print lng\n"
- "print '++++++++',s,'+++++++++++++'\n"
+ "print(lng)\n"
+ "print('++++++++',s,'+++++++++++++')\n"
"ob=o\n"
"seqstr=['aaa','bbb']\n"
"seqobj=[o,o,o,o]\n"
string s = ss.str();
ElementaryNode* node = _myRuntime->createScriptNode("",s);
_nodeMap[s] = node;
- ((InlineNode*) node)->setScript("print li\n"
- "print 'lili=',lili\n"
- "print 'lstr=',lstr\n"
- "print 'lobj=',lobj\n"
- "print 'llobj=',llobj\n"
- "print 'objc=',objc\n"
+ ((InlineNode*) node)->setScript("print(li)\n"
+ "print('lili=',lili)\n"
+ "print('lstr=',lstr)\n"
+ "print('lobj=',lobj)\n"
+ "print('llobj=',llobj)\n"
+ "print('objc=',objc)\n"
"li=2*li\n"
);
InputPort *i1 = node->edAddInputPort("li", _tc_seqdble);
string s = ss.str();
ElementaryNode* node = _myRuntime->createScriptNode("",s);
_nodeMap[s] = node;
- ((InlineNode*) node)->setScript("print li\n"
+ ((InlineNode*) node)->setScript("print(li)\n"
"li=[2*e for e in li]\n"
- "print 'obj=',obj\n"
- "print li\n"
- "print lngvec\n"
- "print dblevec\n"
+ "print('obj=',obj)\n"
+ "print(li)\n"
+ "print(lngvec)\n"
+ "print(dblevec)\n"
);
InputPort *i1 = node->edAddInputPort("li", _tc_seqdble);
InputPort *i2 = node->edAddInputPort("obj", _tc_obj);
((ElementaryNode*)_nodeMap["Node_10"])->load();
((ElementaryNode*)_nodeMap["Node_10"])->execute();
// CPPUNIT_ASSERT_DOUBLES_EQUAL(10.51, (ElementaryNode*)_nodeMap["Node_10"])
-
DEBTRACE(" --- execution Python Node_11" );
((ElementaryNode*)_nodeMap["Node_11"])->load();
((ElementaryNode*)_nodeMap["Node_11"])->execute();
((ElementaryNode*)_nodeMap["Node_15"])->load();
((ElementaryNode*)_nodeMap["Node_15"])->execute();
+ std::cerr << __LINE__ << std::endl;
DEBTRACE(" --- execution XML Node_36" );
((ElementaryNode*)_nodeMap["Node_36"])->load();
((ElementaryNode*)_nodeMap["Node_36"])->execute();
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import xmlrpclib,sys
+import xmlrpc.client,sys
data="""
<methodCall>
</methodCall>
"""
def echo(args):
- print args
+ print(args)
return args
f=open("input")
data=f.read()
f.close()
-print data
+print(data)
class Objref:
"""Wrapper for objrefs """
out.write(self.data or "")
out.write("</objref></value>\n")
-xmlrpclib.WRAPPERS=xmlrpclib.WRAPPERS+(Objref,)
+xmlrpc.client.WRAPPERS=xmlrpc.client.WRAPPERS+(Objref,)
def end_objref(self,data):
self.append(Objref(data))
self._value=0
-xmlrpclib.Unmarshaller.end_objref=end_objref
-xmlrpclib.Unmarshaller.dispatch["objref"]=end_objref
+xmlrpc.client.Unmarshaller.end_objref=end_objref
+xmlrpc.client.Unmarshaller.dispatch["objref"]=end_objref
-params, method = xmlrpclib.loads(data)
+params, method = xmlrpc.client.loads(data)
try:
call=eval(method)
response = (response,)
except:
# report exception back to server
- response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % sys.exc_info()[:2]))
+ response = xmlrpc.client.dumps( xmlrpc.client.Fault(1, "%s:%s" % sys.exc_info()[:2]))
else:
- response = xmlrpclib.dumps( response, methodresponse=1)
+ response = xmlrpc.client.dumps( response, methodresponse=1)
-print response
+print(response)
f=open("output",'w')
f.write(response)
f.close()
double x;
if (PyFloat_Check(o))
x=PyFloat_AS_DOUBLE(o);
- else if (PyInt_Check(o))
- x=PyInt_AS_LONG(o);
else if(PyLong_Check(o))
x=PyLong_AsLong(o);
else
static inline long convert(const TypeCode *t,PyObject* o,void*)
{
long l;
- if (PyInt_Check(o))
- l=PyInt_AS_LONG(o);
- else if(PyLong_Check(o))
+ if(PyLong_Check(o))
l=PyLong_AsLong(o);
else
{
static inline std::string convert(const TypeCode *t,PyObject* o,void*)
{
std::string s;
- if (PyString_Check(o))
- s= PyString_AS_STRING(o);
+ if (PyUnicode_Check(o))
+ {
+ Py_ssize_t size;
+ char *ptr = PyUnicode_AsUTF8AndSize(o, &size);
+ if (!ptr)
+ throw YACS::ENGINE::ConversionException("Conversion from PyUnicode to string failed");
+ s.assign(ptr, size);
+ }
else
{
stringstream msg;
bool l;
if (PyBool_Check(o))
l=(o==Py_True);
- else if (PyInt_Check(o))
- l=(PyInt_AS_LONG(o)!=0);
else if(PyLong_Check(o))
l=(PyLong_AsLong(o)!=0);
else
{
static inline std::string convert(const TypeCode *t,PyObject* o,void*,int protocol)
{
- if (PyString_Check(o) && strncmp(t->id(),"python",6)!=0)
+ if (PyUnicode_Check(o) && strncmp(t->id(),"python",6)!=0)
{
// the objref is used by Python as a string (prefix:value) keep it as a string
- return PyString_AS_STRING(o);
+ Py_ssize_t size;
+ std::string s;
+ char *ptr = PyUnicode_AsUTF8AndSize(o, &size);
+ if (!ptr)
+ throw YACS::ENGINE::ConversionException("Conversion from PyUnicode to string failed");
+ s.assign(ptr, size);
+ return s;
}
if(strncmp(t->id(),"python",6)==0)
{
// It's a native Python object pickle it
- PyObject* mod=PyImport_ImportModule("cPickle");
+ PyObject* mod=PyImport_ImportModule("pickle");
PyObject *pickled=PyObject_CallMethod(mod,(char *)"dumps",(char *)"Oi",o,protocol);
- DEBTRACE(PyObject_REPR(pickled) );
+ DEBTRACE(PyObject_Repr(pickled) );
Py_DECREF(mod);
if(pickled==NULL)
{
PyErr_Print();
throw YACS::ENGINE::ConversionException("Problem in convertToYacsObjref<PYTHONImpl");
}
- std::string mystr(PyString_AsString(pickled),PyString_Size(pickled));
+ std::string mystr(PyBytes_AsString(pickled),PyBytes_Size(pickled));
Py_DECREF(pickled);
return mystr;
}
PyErr_Print();
throw YACS::ENGINE::ConversionException("Problem in convertToYacsObjref<PYTHONImpl");
}
- std::string mystr=PyString_AsString(pickled);
+ std::string mystr=PyBytes_AsString(pickled);
Py_DECREF(pickled);
return mystr;
}
PyErr_Print();
throw YACS::ENGINE::ConversionException("Problem in convertToYacsObjref<PYTHONImpl");
}
- std::string mystr=PyString_AsString(pystring);
+ Py_ssize_t size;
+ std::string mystr;
+ char *ptr = PyUnicode_AsUTF8AndSize(pystring, &size);
+ if (!ptr)
+ throw YACS::ENGINE::ConversionException("Conversion from PyUnicode to string failed");
+ mystr.assign(ptr, size);
Py_DECREF(pystring);
return mystr;
}
{
static inline PyObject* convert(const TypeCode *t,std::string& o)
{
- return PyString_FromString(o.c_str());
+ return PyUnicode_FromString(o.c_str());
}
};
template <>
if(t->isA(Runtime::_tc_file))
{
//It's an objref file. Convert it specially
- return PyString_FromString(o.c_str());
+ return PyUnicode_FromString(o.c_str());
}
if(strncmp(t->id(),"python",6)==0)
{
//It's a python pickled object, unpickled it
- PyObject* mod=PyImport_ImportModule("cPickle");
+ PyObject* mod=PyImport_ImportModule("pickle");
PyObject *ob=PyObject_CallMethod(mod,(char *)"loads",(char *)"s#",o.c_str(),o.length());
- DEBTRACE(PyObject_REPR(ob));
+ DEBTRACE(PyObject_Repr(ob));
Py_DECREF(mod);
if(ob==NULL)
{
}
PyGILState_STATE gstate = PyGILState_Ensure();
- PyObject* mod=PyImport_ImportModule("cPickle");
+ PyObject* mod=PyImport_ImportModule("pickle");
PyObject *ob=PyObject_CallMethod(mod,(char *)"loads",(char *)"s#",s,buffer->length());
PyObject *pickled=PyObject_CallMethod(mod,(char *)"dumps",(char *)"Oi",ob,protocol);
- DEBTRACE(PyObject_REPR(pickled));
- std::string mystr=PyString_AsString(pickled);
+ DEBTRACE(PyObject_Repr(pickled));
+ std::string mystr=PyBytes_AsString(pickled);
Py_DECREF(mod);
Py_DECREF(ob);
Py_DECREF(pickled);
PyObject *s;
PyGILState_STATE gstate = PyGILState_Ensure();
s=PyObject_Str(ob);
- std::string ss(PyString_AsString(s),PyString_Size(s));
+ std::string ss(PyBytes_AsString(s),PyBytes_Size(s));
Py_DECREF(s);
PyGILState_Release(gstate);
return ss;
{
if (PyFloat_Check(o))
return true;
- else if (PyInt_Check(o))
- return true;
else if(PyLong_Check(o))
return true;
else
template<>
inline bool checkInt<PYTHONImpl,PyObject*,void*>(const TypeCode *t,PyObject* o,void* aux)
{
- if (PyInt_Check(o) || PyLong_Check(o))
+ if (PyLong_Check(o))
return true;
else
{
{
if (PyBool_Check(o))
return true;
- else if (PyInt_Check(o))
- return true;
else if(PyLong_Check(o))
return true;
else
template<>
inline bool checkString<PYTHONImpl,PyObject*,void*>(const TypeCode *t,PyObject* o,void* aux)
{
- if (PyString_Check(o))
+ if (PyUnicode_Check(o))
return true;
else
{
template<>
inline bool checkObjref<PYTHONImpl,PyObject*,void*>(const TypeCode *t,PyObject* o,void* aux)
{
- if (PyString_Check(o))
+ if (PyUnicode_Check(o))
return true;
if(strncmp(t->id(),"python",6)==0) // a Python object is expected (it's always true)
return true;
#include <libxml/parser.h>
#include <string>
+#if PY_VERSION_HEX < 0x03050000
+static char*
+Py_EncodeLocale(const wchar_t *arg, size_t *size)
+{
+ return _Py_wchar2char(arg, size);
+}
+static wchar_t*
+Py_DecodeLocale(const char *arg, size_t *size)
+{
+ return _Py_char2wchar(arg, size);
+}
+#endif
+
namespace YACS
{
namespace ENGINE
${SALOME_INCL_PATH}
${PTHREAD_INCLUDE_DIRS}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${LIBXML2_INCLUDE_DIR}
${PYTHON_INCLUDE_DIRS}
${PROJECT_BINARY_DIR}/idl
if (!omnipy)
{
PyErr_SetString(PyExc_ImportError,(char*)"Cannot import _omnipy");
- return;
+ return NULL;
}
PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
- api = (omniORBPYAPI*)PyCObject_AsVoidPtr(pyapi);
+ api = (omniORBpyAPI*)PyCapsule_GetPointer(pyapi,"_omnipy.API");
Py_DECREF(pyapi);
%}
# @defreturn list of strings
def keys(self):
- return self.attrib.keys()
+ return list(self.attrib.keys())
##
# Gets element attributes, as a sequence. The attributes are
# @defreturn list of (string, string) tuples
def items(self):
- return self.attrib.items()
+ return list(self.attrib.items())
##
# Creates a tree iterator. The iterator loops over this element
elif tag is ProcessingInstruction:
file.write("<?%s?>" % _escape_cdata(node.text, encoding))
else:
- items = node.items()
+ items = list(node.items())
xmlns_items = [] # new namespaces in this scope
try:
if isinstance(tag, QName) or tag[:1] == "{":
append((event, None))
parser.EndNamespaceDeclHandler = handler
- def next(self):
+ def __next__(self):
while 1:
try:
item = self._events[self._index]
return self
except NameError:
def __getitem__(self, index):
- return self.next()
+ return next(self)
##
# Parses an XML document from a string constant. This function can
fixname = self._fixname
tag = fixname(tag)
attrib = {}
- for key, value in attrib_in.items():
+ for key, value in list(attrib_in.items()):
attrib[fixname(key)] = self._fixtext(value)
return self._target.start(tag, attrib)
}
display(G)
I=invert(G)
- print reachable(G,2)
- print reachable(I,6)
- print reachable(G,2) & reachable(I,6)
+ print(reachable(G,2))
+ print(reachable(I,6))
+ print(reachable(G,2) & reachable(I,6))
if __name__ == "__main__":
test()
"""
tree = ElementTree.ElementTree(file=filename)
root = tree.getroot()
- if debug:print "root.tag:",root.tag,root
+ if debug:print("root.tag:",root.tag,root)
procs=[]
if root.tag == "dataflow":
#only one dataflow
dataflow=root
- if debug:print dataflow
+ if debug:print(dataflow)
proc=SalomeProc(dataflow)
procs.append(proc)
else:
#one or more dataflows. The graph contains macros.
#All macros are defined at the same level in the XML file.
for dataflow in root.findall("dataflow"):
- if debug:print dataflow
+ if debug:print(dataflow)
proc=SalomeProc(dataflow)
- if debug:print "dataflow name:",proc.name
+ if debug:print("dataflow name:",proc.name)
procs.append(proc)
return procs
#Put macros in macro_dict
macro_dict={}
for p in procs:
- if debug:print "proc_name:",p.name,"coupled_node:",p.coupled_node
+ if debug:print("proc_name:",p.name,"coupled_node:",p.coupled_node)
macro_dict[p.name]=p
- if debug:print filename
+ if debug:print(filename)
yacsproc=ProcNode(proc,macro_dict,filename)
return yacsproc.createNode()
n.setScript(self.codes[0])
self.node=n
for para in self.service.inParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
n.edAddInputPort(para.name,typeMap[para.type])
for para in self.service.outParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
n.edAddOutputPort(para.name,typeMap[para.type])
return self.node
r = pilot.getRuntime()
- if self.container.components.has_key(self.sComponent):
+ if self.sComponent in self.container.components:
#a node for this component already exists
compo_node=self.container.components[self.sComponent]
#It's a node associated with another node of the same component instance
#add dataflow ports in out
for para in self.service.inParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#Create the missing type and adds it into types table
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
n.edAddInputPort(para.name,typeMap[para.type])
for para in self.service.outParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#Create the missing type and adds it into types table
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
pout=n.edAddOutputPort(para.name,typeMap[para.type])
#add datastream ports in and out
for para in self.inStreams:
- if debug:print para.name,para.type,para.dependency,para.schema, para.interpolation,
- if debug:print para.extrapolation
+ if debug:print(para.name,para.type,para.dependency,para.schema, para.interpolation, end=' ')
+ if debug:print(para.extrapolation)
pin=n.edAddInputDataStreamPort(para.name,typeMap[streamTypes[para.type]])
for para in self.outStreams:
- if debug:print para.name,para.type,para.dependency,para.values
+ if debug:print(para.name,para.type,para.dependency,para.values)
pout=n.edAddOutputDataStreamPort(para.name,typeMap[streamTypes[para.type]])
for d in self.datas:
n.inner_nodes=loops[n]
n.G=graph.InducedSubgraph(loops[n],G)
- if debug:print "all loops"
- if debug:print loops
+ if debug:print("all loops")
+ if debug:print(loops)
#Get most external loops
- outer_loops=loops.keys()
+ outer_loops=list(loops.keys())
for l in loops:
for ll in outer_loops:
if loops[l] < loops[ll]:
break
#In the end all remaining loops in outer_loops are the most external
- if debug:print outer_loops
+ if debug:print(outer_loops)
#We remove all internal nodes of most external loops
for l in outer_loops:
#outcoming links of internal nodes. Probably not complete.
inputs={}
for link in l.endloop.links:
- if debug:print link.from_node,link.to_node,link.from_param,link.to_param
+ if debug:print(link.from_node,link.to_node,link.from_param,link.to_param)
inputs[link.to_param]=link.from_node,link.from_param
for s in suiv:
for link in s.links:
if link.from_node == l.endloop:
link.from_node,link.from_param=inputs[link.from_param]
- if debug:print link.from_node,link.to_node,link.from_param,link.to_param
+ if debug:print(link.from_node,link.to_node,link.from_param,link.to_param)
if debug:graph.display(G)
"""This method connects the salome macros in macro_dict to the master YACS Proc.
"""
- if debug:print "connect_macros",self.node,macro_dict
+ if debug:print("connect_macros",self.node,macro_dict)
for node in self.G:
if isinstance(node,MacroNode):
#node is a macro, connect its definition to self.
#node.node is the YACS Bloc equivalent to node
p=macro_dict[node.coupled_node]
bloc=node.node
- if debug:print "macronode:",node.name,node.coupled_node,p
+ if debug:print("macronode:",node.name,node.coupled_node,p)
#Create a hierarchical graph from the salome graph
G=p.create_graph()
node.G=G
init.setScript(self.codes[0])
init.setFname(self.fnames[0])
for para in self.service.inParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
init.edAddInputPort(para.name,typeMap[para.type])
for para in self.service.outParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
init.edAddOutputPort(para.name,typeMap[para.type])
bloop.edAddChild(init)
next.setScript(self.codes[2])
next.setFname(self.fnames[2])
for para in self.service.inParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
next.edAddInputPort(para.name,typeMap[para.type])
for para in self.service.outParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
next.edAddOutputPort(para.name,typeMap[para.type])
blnode.edAddChild(next)
more.setScript(self.codes[1])
more.setFname(self.fnames[1])
for para in self.service.inParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
more.edAddInputPort(para.name,typeMap[para.type])
more.edAddOutputPort("DoLoop",typeMap["int"])
for para in self.service.outParameters:
- if not typeMap.has_key(para.type):
+ if para.type not in typeMap:
#create the missing type and add it in type map
typeMap[para.type]= currentProc.createInterfaceTc("",para.type,[objref])
- if not currentProc.typeMap.has_key(para.type):
+ if para.type not in currentProc.typeMap:
currentProc.typeMap[para.type]=typeMap[para.type]
more.edAddOutputPort(para.name,typeMap[para.type])
blnode.edAddChild(more)
currentProc.typeMap["CALCIUM_real"]=typeMap["CALCIUM_real"]
#create all containers
- for name,container in _containers.items():
+ for name,container in list(_containers.items()):
cont=r.createContainer()
cont.setName(name)
cont.setProperty("hostname",container.mach)
#each node has 2 lists of datastream links (inStreams, outStreams)
def parse(self,dataflow):
- if debug:print "All XML nodes"
+ if debug:print("All XML nodes")
for node in dataflow:
- if debug:print node.tag,node
+ if debug:print(node.tag,node)
#Parse dataflow info-list
self.dataflow_info=self.parseService(dataflow.find("info-list/node/service"))
- if debug:print self.dataflow_info
- if debug:print self.dataflow_info.inParameters
- if debug:print self.dataflow_info.outParameters
+ if debug:print(self.dataflow_info)
+ if debug:print(self.dataflow_info.inParameters)
+ if debug:print(self.dataflow_info.outParameters)
if debug:
for para in self.dataflow_info.inParameters:
- print "inParam:",para.name,para.name.split("__",1)
+ print("inParam:",para.name,para.name.split("__",1))
self.name=dataflow.findtext("info-list/node/node-name")
self.coupled_node=dataflow.findtext("info-list/node/coupled-node")
- if debug:print "All XML nodes dataflow/node-list"
+ if debug:print("All XML nodes dataflow/node-list")
nodes=[]
node_dict={}
#Parse all nodes
node.container= getContainer(container)
if not node.container:
node.container=addContainer(container)
- if debug:print "\tcontainer",node.container
+ if debug:print("\tcontainer",node.container)
elif kind == "3":
#It's a python function
node=MacroNode()
node.kind=10
else:
- raise UnknownKind,kind
+ raise UnknownKind(kind)
node.name=name
node.service=None
node.coupled_node=coupled_node
#Put nodes in a dict to ease search
node_dict[node.name]=node
- if debug:print "\tnode-name",node.name
- if debug:print "\tkind",node.kind,node.__class__.__name__
+ if debug:print("\tnode-name",node.name)
+ if debug:print("\tkind",node.kind,node.__class__.__name__)
s=n.find("service")
if s:
#Parse datastream ports
- if debug:print "DataStream ports"
+ if debug:print("DataStream ports")
inStreams=[]
for indata in n.findall("DataStream-list/inParameter"):
inStreams.append(self.parseInData(indata))
outStreams_dict[p.name]=p
node.outStreams=outStreams
node.outStreams_dict=outStreams_dict
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
nodes.append(node)
self.nodes=nodes
<coord-list/>
</link>
"""
- if debug:print "All XML nodes dataflow/link-list"
+ if debug:print("All XML nodes dataflow/link-list")
links=[]
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
for link in dataflow.findall('link-list/link'):
l=Link()
l.from_name=link.findtext("fromnode-name")
l.from_param=link.findtext("fromserviceparameter-name")
l.to_param=link.findtext("toserviceparameter-name")
links.append(l)
- if debug:print "\tfromnode-name",l.from_name
- if debug:print "\tfromserviceparameter-name",l.from_param
- if debug:print "\ttonode-name",l.to_name
- if debug:print "\ttoserviceparameter-name",l.to_param
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\tfromnode-name",l.from_name)
+ if debug:print("\tfromserviceparameter-name",l.from_param)
+ if debug:print("\ttonode-name",l.to_name)
+ if debug:print("\ttoserviceparameter-name",l.to_param)
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
self.links=links
- if debug:print "All XML nodes dataflow/data-list"
+ if debug:print("All XML nodes dataflow/data-list")
datas=[]
for data in dataflow.findall('data-list/data'):
d=self.parseData(data)
datas.append(d)
- if debug:print "\ttonode-name",d.tonode
- if debug:print "\ttoserviceparameter-name",d.tonodeparam
- if debug:print "\tparameter-value",d.value
- if debug:print "\tparameter-type",d.type
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\ttonode-name",d.tonode)
+ if debug:print("\ttoserviceparameter-name",d.tonodeparam)
+ if debug:print("\tparameter-value",d.value)
+ if debug:print("\tparameter-type",d.type)
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
self.datas=datas
def parseService(self,s):
service=Service()
service.name=s.findtext("service-name")
- if debug:print "\tservice-name",service.name
+ if debug:print("\tservice-name",service.name)
inParameters=[]
for inParam in s.findall("inParameter-list/inParameter"):
p=Parameter()
p.name=inParam.findtext("inParameter-name")
p.type=typeName(inParam.findtext("inParameter-type"))
- if debug:print "\tinParameter-name",p.name
- if debug:print "\tinParameter-type",p.type
+ if debug:print("\tinParameter-name",p.name)
+ if debug:print("\tinParameter-type",p.type)
inParameters.append(p)
service.inParameters=inParameters
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
outParameters=[]
for outParam in s.findall("outParameter-list/outParameter"):
p=Parameter()
p.name=outParam.findtext("outParameter-name")
p.type=typeName(outParam.findtext("outParameter-type"))
- if debug:print "\toutParameter-name",p.name
- if debug:print "\toutParameter-type",p.type
+ if debug:print("\toutParameter-name",p.name)
+ if debug:print("\toutParameter-type",p.type)
outParameters.append(p)
service.outParameters=outParameters
- if debug:print "\t++++++++++++++++++++++++++++++++++++++++++++"
+ if debug:print("\t++++++++++++++++++++++++++++++++++++++++++++")
return service
def parseData(self,d):
return da
def parsePyFunction(self,pyfunc):
- if debug:print pyfunc.tag,":",pyfunc
- if debug:print "\tFuncName",pyfunc.findtext("FuncName")
+ if debug:print(pyfunc.tag,":",pyfunc)
+ if debug:print("\tFuncName",pyfunc.findtext("FuncName"))
text=""
for cdata in pyfunc.findall("PyFunc"):
if text:text=text+'\n'
"""
def parseInData(self,d):
- if debug:print d.tag,":",d
+ if debug:print(d.tag,":",d)
p=Parameter()
p.name=d.findtext("inParameter-name")
p.type=typeName(d.findtext("inParameter-type"))
p.schema=d.findtext("inParameter-schema")
p.interpolation=d.findtext("inParameter-interpolation")
p.extrapolation=d.findtext("inParameter-extrapolation")
- if debug:print "\tinParameter-name",p.name
+ if debug:print("\tinParameter-name",p.name)
return p
def parseOutData(self,d):
- if debug:print d.tag,":",d
+ if debug:print(d.tag,":",d)
p=Parameter()
p.name=d.findtext("outParameter-name")
p.type=typeName(d.findtext("outParameter-type"))
p.dependency=d.findtext("outParameter-dependency")
p.values=d.findtext("outParameter-values")
- if debug:print "\toutParameter-name",p.name
+ if debug:print("\toutParameter-name",p.name)
return p
def create_graph(self):
from_node=self.node_dict[link.from_name]
if link.from_param == "Gate" or link.to_param == "Gate":
#control link salome : add to_name node to neighbours
- if debug:print "add control link",link.from_name,link.to_name
+ if debug:print("add control link",link.from_name,link.to_name)
G[self.node_dict[link.from_name]].add(self.node_dict[link.to_name])
- elif from_node.outStreams_dict.has_key(link.from_param):
+ elif link.from_param in from_node.outStreams_dict:
# datastream link :
# 1- add link in link list
# 2- add in link references on from_node and to_node
- if debug:print "add stream link",link.from_name,link.to_name
+ if debug:print("add stream link",link.from_name,link.to_name)
self.node_dict[link.to_name].inStreamLinks.append(link)
self.node_dict[link.from_name].outStreamLinks.append(link)
link.from_node=self.node_dict[link.from_name]
if isinstance(to_node,LoopNode):
# If it's the link from EndOfLoop to Loop , we ignore it
if to_node.coupled_node == from_node.name:
- if debug:print "backlink loop:",from_node,to_node
+ if debug:print("backlink loop:",from_node,to_node)
#ignored
continue
- if debug:print "add dataflow link",link.from_name,link.to_name
+ if debug:print("add dataflow link",link.from_name,link.to_name)
G[self.node_dict[link.from_name]].add(self.node_dict[link.to_name])
if link.from_param != "DoLoop" and link.to_param != "DoLoop":
and isinstance(self.node_dict[link.to_name],InlineNode):
#Store the end loop inline node in attribute endloop
#self.node_dict[link.to_name] is the end node of the head loop node self.node_dict[link.from_name]
- if debug:print "add loop",link.from_name,link.to_name
+ if debug:print("add loop",link.from_name,link.to_name)
self.node_dict[link.from_name].endloop=self.node_dict[link.to_name]
self.node_dict[link.to_name].loop=self.node_dict[link.from_name]
for data in self.datas:
- if debug:print "datas",data
+ if debug:print("datas",data)
self.node_dict[data.tonode].datas.append(data)
self.G=G
salomeFile=sys.argv[1]
convertedFile=sys.argv[2]
except :
- print usage%(sys.argv[0])
+ print(usage%(sys.argv[0]))
sys.exit(3)
SALOMERuntime.RuntimeSALOME_setRuntime()
logger=p.getLogger("parser")
if not logger.isEmpty():
- print logger.getStr()
+ print(logger.getStr())
sys.exit(1)
if __name__ == "__main__":
<PyFunc><![CDATA[ index = min ]]></PyFunc>
<PyFunc><![CDATA[ else : ]]></PyFunc>
<PyFunc><![CDATA[ index = max ]]></PyFunc>
- <PyFunc><![CDATA[ print "Init :" ]]></PyFunc>
- <PyFunc><![CDATA[ print index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
+ <PyFunc><![CDATA[ print("Init :") ]]></PyFunc>
+ <PyFunc><![CDATA[ print(index,min,max,couronne,Rcouronne,Rsphere) ]]></PyFunc>
<PyFunc><![CDATA[ couronne.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
<PyFunc><![CDATA[?]]></PyFunc>
<PyFunc><![CDATA[ OutLoop = 0 ]]></PyFunc>
<PyFunc><![CDATA[ if max > index : ]]></PyFunc>
<PyFunc><![CDATA[ OutLoop = 1 ]]></PyFunc>
- <PyFunc><![CDATA[ print "More :" ]]></PyFunc>
- <PyFunc><![CDATA[ print OutLoop,index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
+ <PyFunc><![CDATA[ print("More :") ]]></PyFunc>
+ <PyFunc><![CDATA[ print(OutLoop,index,min,max,couronne,Rcouronne,Rsphere) ]]></PyFunc>
<PyFunc><![CDATA[ couronne.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return OutLoop,index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
<PyFunc><![CDATA[?]]></PyFunc>
<FuncName>Next</FuncName>
<PyFunc><![CDATA[def Next(index,min,max,couronne,Rcouronne,Rsphere): ]]></PyFunc>
<PyFunc><![CDATA[ index = index + 1 ]]></PyFunc>
- <PyFunc><![CDATA[ print "Next :" ]]></PyFunc>
- <PyFunc><![CDATA[ print index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
+ <PyFunc><![CDATA[ print("Next :") ]]></PyFunc>
+ <PyFunc><![CDATA[ print(index,min,max,couronne,Rcouronne,Rsphere) ]]></PyFunc>
<PyFunc><![CDATA[ couronne.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return index,min,max,couronne,Rcouronne,Rsphere ]]></PyFunc>
<PyFunc><![CDATA[?]]></PyFunc>
<PyFunc><![CDATA[ aVisu = lcc.FindOrLoadComponent("FactoryServer","VISU") ]]></PyFunc>
<PyFunc><![CDATA[ aStudy = StudyManager.GetStudyByID(1) ]]></PyFunc>
<PyFunc><![CDATA[ aVisu.SetCurrentStudy(aStudy) ]]></PyFunc>
- <PyFunc><![CDATA[ print "InitDisplay --> aVisu ", aVisu ]]></PyFunc>
+ <PyFunc><![CDATA[ print("InitDisplay --> aVisu ", aVisu) ]]></PyFunc>
<PyFunc><![CDATA[ time.sleep(2) ]]></PyFunc>
<PyFunc><![CDATA[ aViewManager=aVisu.GetViewManager() ]]></PyFunc>
- <PyFunc><![CDATA[ print "InitDisplay --> aViewManager ", aViewManager ]]></PyFunc>
+ <PyFunc><![CDATA[ print("InitDisplay --> aViewManager ", aViewManager) ]]></PyFunc>
<PyFunc><![CDATA[ #time.sleep(2) ]]></PyFunc>
<PyFunc><![CDATA[ #aView=aViewManager.GetCurrentView() ]]></PyFunc>
<PyFunc><![CDATA[ aView=aViewManager.Create3DView() ]]></PyFunc>
- <PyFunc><![CDATA[ print "InitDisplay --> aView ", aView ]]></PyFunc>
+ <PyFunc><![CDATA[ print("InitDisplay --> aView ", aView) ]]></PyFunc>
<PyFunc><![CDATA[ #time.sleep(2) ]]></PyFunc>
<PyFunc><![CDATA[ medFile = "TimeStamps.med" ]]></PyFunc>
<PyFunc><![CDATA[ medFile = os.getenv('DATA_DIR') + '/MedFiles/' + medFile ]]></PyFunc>
<PyFunc><![CDATA[ myResult = aVisu.ImportFile(medFile) ]]></PyFunc>
- <PyFunc><![CDATA[ print "InitDisplay --> myResult ", myResult ]]></PyFunc>
+ <PyFunc><![CDATA[ print("InitDisplay --> myResult ", myResult) ]]></PyFunc>
<PyFunc><![CDATA[ return aVisu,aView,myResult ]]></PyFunc>
</PyFunction> </PyFunction-list>
<creation-date>8/4/2005 - 14:3:47</creation-date>
<PyFunc><![CDATA[ index = min ]]></PyFunc>
<PyFunc><![CDATA[ else : ]]></PyFunc>
<PyFunc><![CDATA[ index = max ]]></PyFunc>
- <PyFunc><![CDATA[ print "---- Init ",index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc>
+ <PyFunc><![CDATA[ print("---- Init ",index,min,max,aVisu,aView,myResult,x1) ]]></PyFunc>
<PyFunc><![CDATA[ aView.Register() ]]></PyFunc>
<PyFunc><![CDATA[ myResult.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc> </PyFunction>
<PyFunc><![CDATA[ DoLoop = 1 ]]></PyFunc>
<PyFunc><![CDATA[ else : ]]></PyFunc>
<PyFunc><![CDATA[ DoLoop = 0 ]]></PyFunc>
- <PyFunc><![CDATA[ print "---- More",index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc>
+ <PyFunc><![CDATA[ print("---- More",index,min,max,aVisu,aView,myResult,x1) ]]></PyFunc>
<PyFunc><![CDATA[ aView.Register() ]]></PyFunc>
<PyFunc><![CDATA[ myResult.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return DoLoop,index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc> </PyFunction>
<PyFunc><![CDATA[def Next(index,min,max,aVisu,aView,myResult,x1): ]]></PyFunc>
<PyFunc><![CDATA[ index = index + 1 ]]></PyFunc>
<PyFunc><![CDATA[ x1=x1+1.0 ]]></PyFunc>
- <PyFunc><![CDATA[ print "---- Next",index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc>
+ <PyFunc><![CDATA[ print("---- Next",index,min,max,aVisu,aView,myResult,x1) ]]></PyFunc>
<PyFunc><![CDATA[ aView.Register() ]]></PyFunc>
<PyFunc><![CDATA[ myResult.Register() ]]></PyFunc>
<PyFunc><![CDATA[ return index,min,max,aVisu,aView,myResult,x1 ]]></PyFunc> </PyFunction> </PyFunction-list>
<PyFunc><![CDATA[import os ]]></PyFunc>
<PyFunc><![CDATA[import time ]]></PyFunc>
<PyFunc><![CDATA[def DisplayVitesse(index,aVisu,aView,aResult,x1): ]]></PyFunc>
- <PyFunc><![CDATA[ print "----- Display 1 index = ", index,aVisu,aView,aResult,x1 ]]></PyFunc>
+ <PyFunc><![CDATA[ print("----- Display 1 index = ", index,aVisu,aView,aResult,x1) ]]></PyFunc>
<PyFunc><![CDATA[ aMeshName ="dom" ]]></PyFunc>
<PyFunc><![CDATA[ myFieldName = "vitesse" ]]></PyFunc>
<PyFunc><![CDATA[ anEntity = VISU.NODE ]]></PyFunc>
<PyFunc><![CDATA[ aMesh = aVisu.MeshOnEntity(aResult, aMeshName, anEntity) ]]></PyFunc>
- <PyFunc><![CDATA[ print "----- Display 2 ", aMesh ]]></PyFunc>
+ <PyFunc><![CDATA[ print("----- Display 2 ", aMesh) ]]></PyFunc>
<PyFunc><![CDATA[ x1=int(x1) ]]></PyFunc>
<PyFunc><![CDATA[ aScalarMap=aVisu.ScalarMapOnField(aResult,aMeshName,anEntity,myFieldName,x1) ]]></PyFunc>
- <PyFunc><![CDATA[ print "----- Display 4" ]]></PyFunc>
+ <PyFunc><![CDATA[ print("----- Display 4") ]]></PyFunc>
<PyFunc><![CDATA[ if aScalarMap is not None: ]]></PyFunc>
<PyFunc><![CDATA[ aScalarMap.SetScaling(VISU.LINEAR) ]]></PyFunc>
<PyFunc><![CDATA[ else: ]]></PyFunc>
- <PyFunc><![CDATA[ print "Null scalar map is created" ]]></PyFunc>
- <PyFunc><![CDATA[ print "----- Display 5" ]]></PyFunc>
+ <PyFunc><![CDATA[ print("Null scalar map is created") ]]></PyFunc>
+ <PyFunc><![CDATA[ print("----- Display 5") ]]></PyFunc>
<PyFunc><![CDATA[ aView.DisplayOnly(aScalarMap) ]]></PyFunc>
<PyFunc><![CDATA[ aView.FitAll() ]]></PyFunc>
<PyFunc><![CDATA[ aView.Update() ]]></PyFunc>
- <PyFunc><![CDATA[ print "----- Display 6" ]]></PyFunc>
+ <PyFunc><![CDATA[ print("----- Display 6") ]]></PyFunc>
<PyFunc><![CDATA[ theResult=aResult ]]></PyFunc>
<PyFunc><![CDATA[ #time.sleep(2) ]]></PyFunc>
<PyFunc><![CDATA[ theResult.Register() ]]></PyFunc>
AC_MSG_CHECKING(python extra libraries)
PYTHON_EXTRA_LIBS=`$PYTHON -c "import distutils.sysconfig; \
conf = distutils.sysconfig.get_config_var; \
- print conf('LOCALMODLIBS')+' '+conf('LIBS')"
+ print(conf('LOCALMODLIBS')+' '+conf('LIBS'))"
AC_MSG_RESULT($PYTHON_EXTRA_LIBS)`
AC_SUBST(PYTHON_EXTRA_LIBS)
])
AC_SUBST(PYTHONHOME)
changequote(<<, >>)dnl
- PYTHON_VERSION=`$PYTHON -c "import sys; print sys.version[:3]"`
+ PYTHON_VERSION=`$PYTHON -c "import sys; print(sys.version[:3])"`
changequote([, ])dnl
AC_SUBST(PYTHON_VERSION)
dnl to know which OS Python thinks this is.
AC_SUBST(PYTHON_PLATFORM)
- PYTHON_PLATFORM=`$PYTHON -c "import sys; print sys.platform"`
+ PYTHON_PLATFORM=`$PYTHON -c "import sys; print(sys.platform)"`
AC_SUBST(PYTHON_SITE)
AC_ARG_WITH(python-site,
class Cpp_Template_
{
-// Méthodes publiques
+// Méthodes publiques
public:
Cpp_Template_();
MEDMEM::FIELD<double>* createField();
pass
#
#
-print "Test Program of Cpp_Template_ component"
+print("Test Program of Cpp_Template_ component")
# ...
AC_MSG_CHECKING(python extra libraries)
PYTHON_EXTRA_LIBS=`$PYTHON -c "import distutils.sysconfig; \
conf = distutils.sysconfig.get_config_var; \
- print conf('LOCALMODLIBS')+' '+conf('LIBS')"
+ print(conf('LOCALMODLIBS')+' '+conf('LIBS'))"
AC_MSG_RESULT($PYTHON_EXTRA_LIBS)`
AC_SUBST(PYTHON_EXTRA_LIBS)
])
[command line options] :
--help : affichage de l'aide
--gui : lancement du GUI
---logger : redirection des messages dans un fichier
---xterm : les serveurs ouvrent une fenêtre xterm et les messages sont affichés dans cette fenêtre
---modules=module1,module2,... : où modulen est le nom d'un module Salome à charger dans le catalogue
+--logger : redirection des messages dans un fichier
+--xterm : les serveurs ouvrent une fenêtre xterm et les messages sont affichés dans cette fenêtre
+--modules=module1,module2,... : où modulen est le nom d'un module Salome à charger dans le catalogue
--containers=cpp,python,superv: lancement des containers cpp, python et de supervision
---killall : arrêt des serveurs de salome
+--killall : arrêt des serveurs de salome
- La variable d'environnement <modulen>_ROOT_DIR doit etre préalablement
- positionnée (modulen doit etre en majuscule).
+ La variable d'environnement <modulen>_ROOT_DIR doit etre préalablement
+ positionnée (modulen doit etre en majuscule).
KERNEL_ROOT_DIR est obligatoire.
"""
# -----------------------------------------------------------------------------
#
-# Fonction d'arrêt de salome
+# Fonction d'arrêt de salome
#
def killSalome():
- print "arret des serveurs SALOME"
- for pid, cmd in process_id.items():
- print "arret du process %s : %s"% (pid, cmd[0])
- try:
- os.kill(pid,signal.SIGKILL)
- except:
- print " ------------------ process %s : %s inexistant"% (pid, cmd[0])
- print "arret du naming service"
- os.system("killall -9 omniNames")
-
+ print("arret des serveurs SALOME")
+ for pid, cmd in list(process_id.items()):
+ print("arret du process %s : %s"% (pid, cmd[0]))
+ try:
+ os.kill(pid,signal.SIGKILL)
+ except:
+ print(" ------------------ process %s : %s inexistant"% (pid, cmd[0]))
+ print("arret du naming service")
+ os.system("killall -9 omniNames")
+
# -----------------------------------------------------------------------------
#
# Fonction message
#
def message(code, msg=''):
- if msg: print msg
+ if msg: print(msg)
sys.exit(code)
import sys,os,string,glob,time,signal,pickle,getopt
with_container_superv=0
try:
- for o, a in opts:
- if o in ('-h', '--help'):
- print usage
- sys.exit(1)
- elif o in ('-g', '--gui'):
- with_gui=1
- elif o in ('-l', '--logger'):
- with_logger=1
- elif o in ('-x', '--xterm'):
- with_xterm=1
- elif o in ('-m', '--modules'):
- liste_modules = [x.upper() for x in a.split(',')]
- elif o in ('-c', '--containers'):
- liste_containers = [x.lower() for x in a.split(',')]
- for r in liste_containers:
- if r not in ('cpp', 'python', 'superv'):
- message(1, 'Invalid -c/--containers option: %s' % a)
- if 'cpp' in liste_containers:
- with_container_cpp=1
- else:
- with_container_cpp=0
- if 'python' in liste_containers:
- with_container_python=1
- else:
- with_container_python=0
- if 'superv' in liste_containers:
- with_container_superv=1
- else:
- with_container_superv=0
- elif o in ('-k', '--killall'):
- filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
- #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
- found = 0
- try:
- fpid=open(filedict, 'r')
- found = 1
- except:
- print "le fichier %s des process SALOME n'est pas accessible"% filedict
-
- if found:
- process_id=pickle.load(fpid)
- fpid.close()
- killSalome()
- process_id={}
- os.remove(filedict)
-
-except getopt.error, msg:
- print usage
- sys.exit(1)
+ for o, a in opts:
+ if o in ('-h', '--help'):
+ print(usage)
+ sys.exit(1)
+ elif o in ('-g', '--gui'):
+ with_gui=1
+ elif o in ('-l', '--logger'):
+ with_logger=1
+ elif o in ('-x', '--xterm'):
+ with_xterm=1
+ elif o in ('-m', '--modules'):
+ liste_modules = [x.upper() for x in a.split(',')]
+ elif o in ('-c', '--containers'):
+ liste_containers = [x.lower() for x in a.split(',')]
+ for r in liste_containers:
+ if r not in ('cpp', 'python', 'superv'):
+ message(1, 'Invalid -c/--containers option: %s' % a)
+ if 'cpp' in liste_containers:
+ with_container_cpp=1
+ else:
+ with_container_cpp=0
+ if 'python' in liste_containers:
+ with_container_python=1
+ else:
+ with_container_python=0
+ if 'superv' in liste_containers:
+ with_container_superv=1
+ else:
+ with_container_superv=0
+ elif o in ('-k', '--killall'):
+ filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
+ #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
+ found = 0
+ try:
+ fpid=open(filedict, 'r')
+ found = 1
+ except:
+ print("le fichier %s des process SALOME n'est pas accessible"% filedict)
+
+ if found:
+ process_id=pickle.load(fpid)
+ fpid.close()
+ killSalome()
+ process_id={}
+ os.remove(filedict)
+
+except getopt.error as msg:
+ print(usage)
+ sys.exit(1)
# -----------------------------------------------------------------------------
#
-# Vérification des variables d'environnement
+# Vérification des variables d'environnement
#
try:
- kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
- modules_root_dir["KERNEL"]=kernel_root_dir
+ kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
+ modules_root_dir["KERNEL"]=kernel_root_dir
except:
- print usage
- sys.exit(1)
+ print(usage)
+ sys.exit(1)
for module in liste_modules :
- try:
- module=module.upper()
- module_root_dir=os.environ[module +"_ROOT_DIR"]
- modules_root_dir[module]=module_root_dir
- except:
- print usage
- sys.exit(1)
+ try:
+ module=module.upper()
+ module_root_dir=os.environ[module +"_ROOT_DIR"]
+ modules_root_dir[module]=module_root_dir
+ except:
+ print(usage)
+ sys.exit(1)
# il faut KERNEL en premier dans la liste des modules
# - l'ordre des modules dans le catalogue sera identique
-# - la liste des modules presents dans le catalogue est exploitée pour charger les modules CORBA python,
+# - la liste des modules presents dans le catalogue est exploitée pour charger les modules CORBA python,
# il faut charger les modules python du KERNEL en premier
if "KERNEL" in liste_modules:liste_modules.remove("KERNEL")
#print liste_modules
#print modules_root_dir
-os.environ["SALOMEPATH"]=":".join(modules_root_dir.values())
+os.environ["SALOMEPATH"]=":".join(list(modules_root_dir.values()))
if "SUPERV" in liste_modules:with_container_superv=1
# -----------------------------------------------------------------------------
#
-# Définition des classes d'objets pour le lancement des Server CORBA
+# Définition des classes d'objets pour le lancement des Server CORBA
#
class Server:
- CMD=[]
- if with_xterm:
- ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-e']
- else:
- ARGS=[]
-
- def run(self):
- args = self.ARGS+self.CMD
- #print "args = ", args
- pid = os.spawnvp(os.P_NOWAIT, args[0], args)
- process_id[pid]=self.CMD
+ CMD=[]
+ if with_xterm:
+ ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-e']
+ else:
+ ARGS=[]
+
+ def run(self):
+ args = self.ARGS+self.CMD
+ #print "args = ", args
+ pid = os.spawnvp(os.P_NOWAIT, args[0], args)
+ process_id[pid]=self.CMD
class CatalogServer(Server):
- SCMD1=['SALOME_ModuleCatalog_Server','-common']
- SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml']
-
- def setpath(self,liste_modules):
- cata_path=[]
- for module in liste_modules:
- module_root_dir=modules_root_dir[module]
- module_cata=module+"Catalog.xml"
- print " ", module_cata
- cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata)))
- self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+ SCMD1=['SALOME_ModuleCatalog_Server','-common']
+ SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml']
+
+ def setpath(self,liste_modules):
+ cata_path=[]
+ for module in liste_modules:
+ module_root_dir=modules_root_dir[module]
+ module_cata=module+"Catalog.xml"
+ print(" ", module_cata)
+ cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata)))
+ self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
class SalomeDSServer(Server):
- CMD=['SALOMEDS_Server']
+ CMD=['SALOMEDS_Server']
class RegistryServer(Server):
- CMD=['SALOME_Registry_Server', '--salome_session','theSession']
+ CMD=['SALOME_Registry_Server', '--salome_session','theSession']
class ContainerCPPServer(Server):
- CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
class ContainerPYServer(Server):
- CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
class ContainerSUPERVServer(Server):
- CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
class LoggerServer(Server):
- CMD=['SALOME_Logger_Server', 'logger.log']
+ CMD=['SALOME_Logger_Server', 'logger.log']
class SessionLoader(Server):
- CMD=['SALOME_Session_Loader']
- if with_container_cpp:
- CMD=CMD+['CPP']
- if with_container_python:
- CMD=CMD+['PY']
- if with_container_superv:
- CMD=CMD+['SUPERV']
- if with_gui:
- CMD=CMD+['GUI']
+ CMD=['SALOME_Session_Loader']
+ if with_container_cpp:
+ CMD=CMD+['CPP']
+ if with_container_python:
+ CMD=CMD+['PY']
+ if with_container_superv:
+ CMD=CMD+['SUPERV']
+ if with_gui:
+ CMD=CMD+['GUI']
class SessionServer(Server):
- CMD=['SALOME_Session_Server']
+ CMD=['SALOME_Session_Server']
class NotifyServer(Server):
- CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior']
+ CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior']
# -----------------------------------------------------------------------------
#
#
def test(clt):
- """
- Test function that creates an instance of HXX2SALOME_GENERIC_CLASS_NAME component
- usage : hello=test(clt)
- """
- # create an LifeCycleCORBA instance
- import LifeCycleCORBA
- lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb)
- import HXX2SALOME_GENERIC_CLASS_NAME_ORB
- hello = lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
- return hello
+ """
+ Test function that creates an instance of HXX2SALOME_GENERIC_CLASS_NAME component
+ usage : hello=test(clt)
+ """
+ # create an LifeCycleCORBA instance
+ import LifeCycleCORBA
+ lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb)
+ import HXX2SALOME_GENERIC_CLASS_NAME_ORB
+ hello = lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
+ return hello
# -----------------------------------------------------------------------------
#
#
def add_path(directory):
- os.environ["PATH"]=directory + ":" + os.environ["PATH"]
+ os.environ["PATH"]=directory + ":" + os.environ["PATH"]
def add_ld_library_path(directory):
- os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"]
+ os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"]
def add_python_path(directory):
- os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"]
- sys.path[:0]=[directory]
+ os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"]
+ sys.path[:0]=[directory]
# -----------------------------------------------------------------------------
#
#
def startGUI():
- import SALOME
- session=clt.waitNS("/Kernel/Session",SALOME.Session)
+ import SALOME
+ session=clt.waitNS("/Kernel/Session",SALOME.Session)
+
+ #
+ # Activation du GUI de Session Server
+ #
+
+ session.GetInterface()
- #
- # Activation du GUI de Session Server
- #
-
- session.GetInterface()
-
#
# -----------------------------------------------------------------------------
#
def startSalome():
- #
- # Lancement Session Loader
- #
- SessionLoader().run()
-
- #
- # Initialisation ORB et Naming Service
- #
- clt=orbmodule.client()
-
- # (non obligatoire) Lancement Logger Server et attente de sa
- # disponibilite dans le naming service
- #
- if with_logger:
- LoggerServer().run()
- clt.waitLogger("Logger")
-
- #
- # Lancement Registry Server
- #
- RegistryServer().run()
-
- #
- # Attente de la disponibilité du Registry dans le Naming Service
- #
- clt.waitNS("/Registry")
-
- #
- # Lancement Catalog Server
- #
- cataServer=CatalogServer()
- cataServer.setpath(liste_modules)
- cataServer.run()
-
- #
- # Attente de la disponibilité du Catalog Server dans le Naming Service
- #
- import SALOME_ModuleCatalog
- clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
-
- #
- # Lancement SalomeDS Server
- #
- os.environ["CSF_PluginDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
- os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
- SalomeDSServer().run()
-
- if "GEOM" in liste_modules:
- print "GEOM OCAF Resources"
- os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share","salome","resources")
-
-
- #
- # Attente de la disponibilité du SalomeDS dans le Naming Service
- #
- clt.waitNS("/myStudyManager")
-
- #
- # Lancement Session Server
- #
- SessionServer().run()
-
- #
- # Attente de la disponibilité du Session Server dans le Naming Service
- #
- import SALOME
- session=clt.waitNS("/Kernel/Session",SALOME.Session)
-
- #
- # Lancement containers
- #
- theComputer = os.getenv("HOSTNAME")
- theComputer = theComputer.split('.')[0]
-
- #
- # Lancement Container C++ local
- #
- if with_container_cpp:
- ContainerCPPServer().run()
- #
- # Attente de la disponibilité du Container C++ local
- # dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
- #
- # Lancement Container Python local
- #
- if with_container_python:
- ContainerPYServer().run()
- #
- # Attente de la disponibilité du Container Python local
- # dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
-
- if with_container_superv:
- #
- # Lancement Container Supervision local
- #
- ContainerSUPERVServer().run()
- #
- # Attente de la disponibilité du Container Supervision local
+ #
+ # Lancement Session Loader
+ #
+ SessionLoader().run()
+
+ #
+ # Initialisation ORB et Naming Service
+ #
+ clt=orbmodule.client()
+
+ # (non obligatoire) Lancement Logger Server et attente de sa
+ # disponibilite dans le naming service
+ #
+ if with_logger:
+ LoggerServer().run()
+ clt.waitLogger("Logger")
+
+ #
+ # Lancement Registry Server
+ #
+ RegistryServer().run()
+
+ #
+ # Attente de la disponibilité du Registry dans le Naming Service
+ #
+ clt.waitNS("/Registry")
+
+ #
+ # Lancement Catalog Server
+ #
+ cataServer=CatalogServer()
+ cataServer.setpath(liste_modules)
+ cataServer.run()
+
+ #
+ # Attente de la disponibilité du Catalog Server dans le Naming Service
+ #
+ import SALOME_ModuleCatalog
+ clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
+
+ #
+ # Lancement SalomeDS Server
+ #
+ os.environ["CSF_PluginDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
+ os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
+ SalomeDSServer().run()
+
+ if "GEOM" in liste_modules:
+ print("GEOM OCAF Resources")
+ os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share","salome","resources")
+
+
+ #
+ # Attente de la disponibilité du SalomeDS dans le Naming Service
+ #
+ clt.waitNS("/myStudyManager")
+
+ #
+ # Lancement Session Server
+ #
+ SessionServer().run()
+
+ #
+ # Attente de la disponibilité du Session Server dans le Naming Service
+ #
+ import SALOME
+ session=clt.waitNS("/Kernel/Session",SALOME.Session)
+
+ #
+ # Lancement containers
+ #
+ theComputer = os.getenv("HOSTNAME")
+ theComputer = theComputer.split('.')[0]
+
+ #
+ # Lancement Container C++ local
+ #
+ if with_container_cpp:
+ ContainerCPPServer().run()
+ #
+ # Attente de la disponibilité du Container C++ local
# dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
- #
- # Activation du GUI de Session Server
- #
- #session.GetInterface()
+ #
+ clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
+ #
+ # Lancement Container Python local
+ #
+ if with_container_python:
+ ContainerPYServer().run()
+ #
+ # Attente de la disponibilité du Container Python local
+ # dans le Naming Service
+ #
+ clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
+
+ if with_container_superv:
+ #
+ # Lancement Container Supervision local
+ #
+ ContainerSUPERVServer().run()
+ #
+ # Attente de la disponibilité du Container Supervision local
+ # dans le Naming Service
+ #
+ clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
+ #
+ # Activation du GUI de Session Server
+ #
+ #session.GetInterface()
- end_time = os.times()
- print
- print "Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4])
+ end_time = os.times()
+ print()
+ print("Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4]))
- return clt
+ return clt
#
# -----------------------------------------------------------------------------
#
if __name__ == "__main__":
- clt=None
- try:
- clt = startSalome()
- except:
- print
- print
- print "--- erreur au lancement Salome ---"
-
- #print process_id
-
-
- filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
- #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
-
- fpid=open(filedict, 'w')
- pickle.dump(process_id,fpid)
- fpid.close()
-
- print """
-
-Sauvegarde du dictionnaire des process dans , %s
-Pour tuer les process SALOME, executer : python killSalome.py depuis
-une console, ou bien killSalome() depuis le present interpreteur,
-s'il n'est pas fermé.
-
-runSalome, avec l'option --killall, commence par tuer les process restants
-d'une execution précédente.
-
-Pour lancer uniquement le GUI, executer startGUI() depuis le present interpreteur,
-s'il n'est pas fermé.
-
-""" % filedict
-
- #
- # Impression arborescence Naming Service
- #
-
- if clt != None:
- print
- print " --- registered objects tree in Naming Service ---"
- clt.showNS()
- session=clt.waitNS("/Kernel/Session")
- catalog=clt.waitNS("/Kernel/ModulCatalog")
- import socket
- container = clt.waitNS("/Containers/" + socket.gethostname().split('.')[0] + "/FactoryServerPy")
-
- if os.path.isfile("~/.salome/pystartup"):
- f=open(os.path.expanduser("~/.salome/pystartup"),'w')
- PYTHONSTARTUP=f.read()
- f.close()
- else:
- PYTHONSTARTUP="""
-# Add auto-completion and a stored history file of commands to your Python
-# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
-# bound to the TAB key by default (you can change it - see readline docs).
-#
-# Store the history in ~/.salome/pyhistory,
-#
-import atexit
-import os
-import readline
-import rlcompleter
-readline.parse_and_bind('tab: complete')
+ clt=None
+ try:
+ clt = startSalome()
+ except:
+ print()
+ print()
+ print("--- erreur au lancement Salome ---")
+
+ #print process_id
+
+
+ filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
+ #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
+
+ fpid=open(filedict, 'w')
+ pickle.dump(process_id,fpid)
+ fpid.close()
+
+ print("""
+
+ Sauvegarde du dictionnaire des process dans , %s
+ Pour tuer les process SALOME, executer : python killSalome.py depuis
+ une console, ou bien killSalome() depuis le present interpreteur,
+ s'il n'est pas fermé.
+
+ runSalome, avec l'option --killall, commence par tuer les process restants
+ d'une execution précédente.
+
+ Pour lancer uniquement le GUI, executer startGUI() depuis le present interpreteur,
+ s'il n'est pas fermé.
+
+ """ % filedict)
+
+ #
+ # Impression arborescence Naming Service
+ #
+
+ if clt != None:
+ print()
+ print(" --- registered objects tree in Naming Service ---")
+ clt.showNS()
+ session=clt.waitNS("/Kernel/Session")
+ catalog=clt.waitNS("/Kernel/ModulCatalog")
+ import socket
+ container = clt.waitNS("/Containers/" + socket.gethostname().split('.')[0] + "/FactoryServerPy")
+
+ if os.path.isfile("~/.salome/pystartup"):
+ f=open(os.path.expanduser("~/.salome/pystartup"),'w')
+ PYTHONSTARTUP=f.read()
+ f.close()
+ else:
+ PYTHONSTARTUP="""
+ # Add auto-completion and a stored history file of commands to your Python
+ # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
+ # bound to the TAB key by default (you can change it - see readline docs).
+ #
+ # Store the history in ~/.salome/pyhistory,
+ #
+ import atexit
+ import os
+ import readline
+ import rlcompleter
+ readline.parse_and_bind('tab: complete')
-historyPath = os.path.expanduser("~/.salome/pyhistory")
+ historyPath = os.path.expanduser("~/.salome/pyhistory")
-def save_history(historyPath=historyPath):
- import readline
- readline.write_history_file(historyPath)
+ def save_history(historyPath=historyPath):
+ import readline
+ readline.write_history_file(historyPath)
-if os.path.exists(historyPath):
- readline.read_history_file(historyPath)
+ if os.path.exists(historyPath):
+ readline.read_history_file(historyPath)
-atexit.register(save_history)
-del os, atexit, readline, rlcompleter, save_history, historyPath
-"""
- f=open(os.path.expanduser("~/.salome/pystartup"),'w')
- f.write(PYTHONSTARTUP)
- f.close()
+ atexit.register(save_history)
+ del os, atexit, readline, rlcompleter, save_history, historyPath
+ """
+ f=open(os.path.expanduser("~/.salome/pystartup"),'w')
+ f.write(PYTHONSTARTUP)
+ f.close()
- exec PYTHONSTARTUP in {}
-
+ exec(PYTHONSTARTUP, {})
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-mport salome
+import salome
import HXX2SALOME_GENERIC_CLASS_NAME_ORB
myHXX2SALOME_GENERIC_CLASS_NAME = salome.lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
#
#
-print "Hello HXX2SALOME_GENERIC_CLASS_NAME"
+print("Hello HXX2SALOME_GENERIC_CLASS_NAME")
# Test here some of HXX2SALOME_GENERIC_CLASS_NAME methods ...
msgstr "Ceci est un simple test"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::INF_HXX2SALOME_GENERIC_CLASS_NAME_CHECK"
-msgstr "Cochée"
+msgstr "Cochée"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::INF_HXX2SALOME_GENERIC_CLASS_NAME_UNCHECK"
-msgstr "Décochée"
+msgstr "Décochée"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::RES_HXX2SALOME_GENERIC_CLASS_NAME_TITLE"
msgstr "Dialogue example de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::RES_HXX2SALOME_GENERIC_CLASS_NAME_TEXT"
-msgstr "Les préférences sont : \n\tCase à cocher : %1\n\tEntier : %2\n\tEntier2 : %3\n\tDouble : %4\n\tTexte : %5"
+msgstr "Les préférences sont : \n\tCase à cocher : %1\n\tEntier : %2\n\tEntier2 : %3\n\tDouble : %4\n\tTexte : %5"
msgid "TLT_MY_NEW_ITEM"
-msgstr "Un article de menu propre à HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Un article de menu propre à HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_MY_NEW_ITEM"
msgstr "Mon menu"
msgid "STS_MY_NEW_ITEM"
-msgstr "Affiche une boîte de dialogue simple"
+msgstr "Affiche une boîte de dialogue simple"
msgid "TLT_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "STS_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_FILE"
msgstr "&File"
#-------------------------------------------------------------------------
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_TAB_GENERAL"
-msgstr "Général"
+msgstr "Général"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_GROUP_DEFAULTS"
-msgstr "Valeurs par défaut"
+msgstr "Valeurs par défaut"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_BOOL"
msgstr "Cochez-moi"
msgstr "Entrez un entier :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SPININT"
-msgstr "Cliquez sur les flèches (entier) :"
+msgstr "Cliquez sur les flèches (entier) :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SPINDBL"
-msgstr "Cliquez sur les flèches (double) :"
+msgstr "Cliquez sur les flèches (double) :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SELECTOR"
msgstr "Choisissez une option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_0"
-msgstr "Première option"
+msgstr "Première option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_1"
msgstr "Seconde option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_2"
-msgstr "Troisième option"
+msgstr "Troisième option"
AC_SUBST(PYTHONHOME)
changequote(<<, >>)dnl
- PYTHON_VERSION=`$PYTHON -c "import sys; print sys.version[:3]"`
+ PYTHON_VERSION=`$PYTHON -c "import sys; print(sys.version[:3])"`
changequote([, ])dnl
AC_SUBST(PYTHON_VERSION)
dnl to know which OS Python thinks this is.
AC_SUBST(PYTHON_PLATFORM)
- PYTHON_PLATFORM=`$PYTHON -c "import sys; print sys.platform"`
+ PYTHON_PLATFORM=`$PYTHON -c "import sys; print(sys.platform)"`
AC_SUBST(PYTHON_SITE)
AC_ARG_WITH(python-site,
import sys, os, string, py_compile
files = '''$*'''
-print 'Byte-compiling python modules...'
+print('Byte-compiling python modules...')
for file in string.split(files):
$trans
if not os.path.exists(path) or not (len(path) >= 3 and path[-3:] == '.py'):
continue
- print file,
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(path)
print" || exit $?
import sys, os, string, py_compile
files = '''$*'''
-print 'Byte-compiling python modules (optimized versions) ...'
+print('Byte-compiling python modules (optimized versions) ...')
for file in string.split(files):
$trans
if not os.path.exists(path) or not (len(path) >= 3 and path[-3:] == '.py'):
continue
- print file,
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(path)
print" 2>/dev/null || :
[command line options] :
--help : affichage de l'aide
--gui : lancement du GUI
---logger : redirection des messages dans un fichier
---xterm : les serveurs ouvrent une fenêtre xterm et les messages sont affichés dans cette fenêtre
---modules=module1,module2,... : où modulen est le nom d'un module Salome à charger dans le catalogue
+--logger : redirection des messages dans un fichier
+--xterm : les serveurs ouvrent une fenêtre xterm et les messages sont affichés dans cette fenêtre
+--modules=module1,module2,... : où modulen est le nom d'un module Salome à charger dans le catalogue
--containers=cpp,python,superv: lancement des containers cpp, python et de supervision
---killall : arrêt des serveurs de salome
+--killall : arrêt des serveurs de salome
- La variable d'environnement <modulen>_ROOT_DIR doit etre préalablement
- positionnée (modulen doit etre en majuscule).
+ La variable d'environnement <modulen>_ROOT_DIR doit etre préalablement
+ positionnée (modulen doit etre en majuscule).
KERNEL_ROOT_DIR est obligatoire.
"""
# -----------------------------------------------------------------------------
#
-# Fonction d'arrêt de salome
+# Fonction d'arrêt de salome
#
def killSalome():
- print "arret des serveurs SALOME"
- for pid, cmd in process_id.items():
- print "arret du process %s : %s"% (pid, cmd[0])
- try:
- os.kill(pid,signal.SIGKILL)
- except:
- print " ------------------ process %s : %s inexistant"% (pid, cmd[0])
- print "arret du naming service"
- os.system("killall -9 omniNames")
-
+ print("arret des serveurs SALOME")
+ for pid, cmd in list(process_id.items()):
+ print("arret du process %s : %s"% (pid, cmd[0]))
+ try:
+ os.kill(pid,signal.SIGKILL)
+ except:
+ print(" ------------------ process %s : %s inexistant"% (pid, cmd[0]))
+ print("arret du naming service")
+ os.system("killall -9 omniNames")
+
# -----------------------------------------------------------------------------
#
# Fonction message
#
def message(code, msg=''):
- if msg: print msg
+ if msg: print(msg)
sys.exit(code)
import sys,os,string,glob,time,signal,pickle,getopt
with_container_superv=0
try:
- for o, a in opts:
- if o in ('-h', '--help'):
- print usage
- sys.exit(1)
- elif o in ('-g', '--gui'):
- with_gui=1
- elif o in ('-l', '--logger'):
- with_logger=1
- elif o in ('-x', '--xterm'):
- with_xterm=1
- elif o in ('-m', '--modules'):
- liste_modules = [x.upper() for x in a.split(',')]
- elif o in ('-c', '--containers'):
- liste_containers = [x.lower() for x in a.split(',')]
- for r in liste_containers:
- if r not in ('cpp', 'python', 'superv'):
- message(1, 'Invalid -c/--containers option: %s' % a)
- if 'cpp' in liste_containers:
- with_container_cpp=1
- else:
- with_container_cpp=0
- if 'python' in liste_containers:
- with_container_python=1
- else:
- with_container_python=0
- if 'superv' in liste_containers:
- with_container_superv=1
- else:
- with_container_superv=0
- elif o in ('-k', '--killall'):
- filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
- #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
- found = 0
- try:
- fpid=open(filedict, 'r')
- found = 1
- except:
- print "le fichier %s des process SALOME n'est pas accessible"% filedict
-
- if found:
- process_id=pickle.load(fpid)
- fpid.close()
- killSalome()
- process_id={}
- os.remove(filedict)
-
-except getopt.error, msg:
- print usage
- sys.exit(1)
+ for o, a in opts:
+ if o in ('-h', '--help'):
+ print(usage)
+ sys.exit(1)
+ elif o in ('-g', '--gui'):
+ with_gui=1
+ elif o in ('-l', '--logger'):
+ with_logger=1
+ elif o in ('-x', '--xterm'):
+ with_xterm=1
+ elif o in ('-m', '--modules'):
+ liste_modules = [x.upper() for x in a.split(',')]
+ elif o in ('-c', '--containers'):
+ liste_containers = [x.lower() for x in a.split(',')]
+ for r in liste_containers:
+ if r not in ('cpp', 'python', 'superv'):
+ message(1, 'Invalid -c/--containers option: %s' % a)
+ if 'cpp' in liste_containers:
+ with_container_cpp=1
+ else:
+ with_container_cpp=0
+ if 'python' in liste_containers:
+ with_container_python=1
+ else:
+ with_container_python=0
+ if 'superv' in liste_containers:
+ with_container_superv=1
+ else:
+ with_container_superv=0
+ elif o in ('-k', '--killall'):
+ filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
+ #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
+ found = 0
+ try:
+ fpid=open(filedict, 'r')
+ found = 1
+ except:
+ print("le fichier %s des process SALOME n'est pas accessible"% filedict)
+
+ if found:
+ process_id=pickle.load(fpid)
+ fpid.close()
+ killSalome()
+ process_id={}
+ os.remove(filedict)
+
+except getopt.error as msg:
+ print(usage)
+ sys.exit(1)
# -----------------------------------------------------------------------------
#
-# Vérification des variables d'environnement
+# Vérification des variables d'environnement
#
try:
- kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
- modules_root_dir["KERNEL"]=kernel_root_dir
+ kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
+ modules_root_dir["KERNEL"]=kernel_root_dir
except:
- print usage
- sys.exit(1)
+ print(usage)
+ sys.exit(1)
for module in liste_modules :
- try:
- module=module.upper()
- module_root_dir=os.environ[module +"_ROOT_DIR"]
- modules_root_dir[module]=module_root_dir
- except:
- print usage
- sys.exit(1)
+ try:
+ module=module.upper()
+ module_root_dir=os.environ[module +"_ROOT_DIR"]
+ modules_root_dir[module]=module_root_dir
+ except:
+ print(usage)
+ sys.exit(1)
# il faut KERNEL en premier dans la liste des modules
# - l'ordre des modules dans le catalogue sera identique
-# - la liste des modules presents dans le catalogue est exploitée pour charger les modules CORBA python,
+# - la liste des modules presents dans le catalogue est exploitée pour charger les modules CORBA python,
# il faut charger les modules python du KERNEL en premier
if "KERNEL" in liste_modules:liste_modules.remove("KERNEL")
#print liste_modules
#print modules_root_dir
-os.environ["SALOMEPATH"]=":".join(modules_root_dir.values())
+os.environ["SALOMEPATH"]=":".join(list(modules_root_dir.values()))
if "SUPERV" in liste_modules:with_container_superv=1
# -----------------------------------------------------------------------------
#
-# Définition des classes d'objets pour le lancement des Server CORBA
+# Définition des classes d'objets pour le lancement des Server CORBA
#
class Server:
- CMD=[]
- if with_xterm:
- ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-e']
- else:
- ARGS=[]
-
- def run(self):
- args = self.ARGS+self.CMD
- #print "args = ", args
- pid = os.spawnvp(os.P_NOWAIT, args[0], args)
- process_id[pid]=self.CMD
+ CMD=[]
+ if with_xterm:
+ ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-e']
+ else:
+ ARGS=[]
+
+ def run(self):
+ args = self.ARGS+self.CMD
+ #print "args = ", args
+ pid = os.spawnvp(os.P_NOWAIT, args[0], args)
+ process_id[pid]=self.CMD
class CatalogServer(Server):
- SCMD1=['SALOME_ModuleCatalog_Server','-common']
- SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml']
-
- def setpath(self,liste_modules):
- cata_path=[]
- for module in liste_modules:
- module_root_dir=modules_root_dir[module]
- module_cata=module+"Catalog.xml"
- print " ", module_cata
- cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata)))
- self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+ SCMD1=['SALOME_ModuleCatalog_Server','-common']
+ SCMD2=['-personal','${HOME}/Salome/resources/CatalogModulePersonnel.xml']
+
+ def setpath(self,liste_modules):
+ cata_path=[]
+ for module in liste_modules:
+ module_root_dir=modules_root_dir[module]
+ module_cata=module+"Catalog.xml"
+ print(" ", module_cata)
+ cata_path.extend(glob.glob(os.path.join(module_root_dir,"share","salome","resources",module_cata)))
+ self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
class SalomeDSServer(Server):
- CMD=['SALOMEDS_Server']
+ CMD=['SALOMEDS_Server']
class RegistryServer(Server):
- CMD=['SALOME_Registry_Server', '--salome_session','theSession']
+ CMD=['SALOME_Registry_Server', '--salome_session','theSession']
class ContainerCPPServer(Server):
- CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_Container','FactoryServer','-ORBInitRef','NameService=corbaname::localhost']
class ContainerPYServer(Server):
- CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_ContainerPy.py','FactoryServerPy','-ORBInitRef','NameService=corbaname::localhost']
class ContainerSUPERVServer(Server):
- CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
+ CMD=['SALOME_Container','SuperVisionContainer','-ORBInitRef','NameService=corbaname::localhost']
class LoggerServer(Server):
- CMD=['SALOME_Logger_Server', 'logger.log']
+ CMD=['SALOME_Logger_Server', 'logger.log']
class SessionLoader(Server):
- CMD=['SALOME_Session_Loader']
- if with_container_cpp:
- CMD=CMD+['CPP']
- if with_container_python:
- CMD=CMD+['PY']
- if with_container_superv:
- CMD=CMD+['SUPERV']
- if with_gui:
- CMD=CMD+['GUI']
+ CMD=['SALOME_Session_Loader']
+ if with_container_cpp:
+ CMD=CMD+['CPP']
+ if with_container_python:
+ CMD=CMD+['PY']
+ if with_container_superv:
+ CMD=CMD+['SUPERV']
+ if with_gui:
+ CMD=CMD+['GUI']
class SessionServer(Server):
- CMD=['SALOME_Session_Server']
+ CMD=['SALOME_Session_Server']
class NotifyServer(Server):
- CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior']
+ CMD=['notifd','-c','${KERNEL_ROOT_DIR}/share/salome/resources/channel.cfg -DFactoryIORFileName=/tmp/${LOGNAME}_rdifact.ior -DChannelIORFileName=/tmp/${LOGNAME}_rdichan.ior']
# -----------------------------------------------------------------------------
#
#
def test(clt):
- """
- Test function that creates an instance of HXX2SALOME_GENERIC_CLASS_NAME component
- usage : hello=test(clt)
- """
- # create an LifeCycleCORBA instance
- import LifeCycleCORBA
- lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb)
- import HXX2SALOME_GENERIC_CLASS_NAME_ORB
- hello = lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
- return hello
+ """
+ Test function that creates an instance of HXX2SALOME_GENERIC_CLASS_NAME component
+ usage : hello=test(clt)
+ """
+ # create an LifeCycleCORBA instance
+ import LifeCycleCORBA
+ lcc = LifeCycleCORBA.LifeCycleCORBA(clt.orb)
+ import HXX2SALOME_GENERIC_CLASS_NAME_ORB
+ hello = lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
+ return hello
# -----------------------------------------------------------------------------
#
#
def add_path(directory):
- os.environ["PATH"]=directory + ":" + os.environ["PATH"]
+ os.environ["PATH"]=directory + ":" + os.environ["PATH"]
def add_ld_library_path(directory):
- os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"]
+ os.environ["LD_LIBRARY_PATH"]=directory + ":" + os.environ["LD_LIBRARY_PATH"]
def add_python_path(directory):
- os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"]
- sys.path[:0]=[directory]
+ os.environ["PYTHONPATH"]=directory + ":" + os.environ["PYTHONPATH"]
+ sys.path[:0]=[directory]
# -----------------------------------------------------------------------------
#
#
def startGUI():
- import SALOME
- session=clt.waitNS("/Kernel/Session",SALOME.Session)
+ import SALOME
+ session=clt.waitNS("/Kernel/Session",SALOME.Session)
+
+ #
+ # Activation du GUI de Session Server
+ #
+
+ session.GetInterface()
- #
- # Activation du GUI de Session Server
- #
-
- session.GetInterface()
-
#
# -----------------------------------------------------------------------------
#
def startSalome():
- #
- # Lancement Session Loader
- #
- SessionLoader().run()
-
- #
- # Initialisation ORB et Naming Service
- #
- clt=orbmodule.client()
-
- # (non obligatoire) Lancement Logger Server et attente de sa
- # disponibilite dans le naming service
- #
- if with_logger:
- LoggerServer().run()
- clt.waitLogger("Logger")
-
- #
- # Lancement Registry Server
- #
- RegistryServer().run()
-
- #
- # Attente de la disponibilité du Registry dans le Naming Service
- #
- clt.waitNS("/Registry")
-
- #
- # Lancement Catalog Server
- #
- cataServer=CatalogServer()
- cataServer.setpath(liste_modules)
- cataServer.run()
-
- #
- # Attente de la disponibilité du Catalog Server dans le Naming Service
- #
- import SALOME_ModuleCatalog
- clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
-
- #
- # Lancement SalomeDS Server
- #
- os.environ["CSF_PluginDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
- os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
- SalomeDSServer().run()
-
- if "GEOM" in liste_modules:
- print "GEOM OCAF Resources"
- os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share","salome","resources")
-
-
- #
- # Attente de la disponibilité du SalomeDS dans le Naming Service
- #
- clt.waitNS("/myStudyManager")
-
- #
- # Lancement Session Server
- #
- SessionServer().run()
-
- #
- # Attente de la disponibilité du Session Server dans le Naming Service
- #
- import SALOME
- session=clt.waitNS("/Kernel/Session",SALOME.Session)
-
- #
- # Lancement containers
- #
- theComputer = os.getenv("HOSTNAME")
- theComputer = theComputer.split('.')[0]
-
- #
- # Lancement Container C++ local
- #
- if with_container_cpp:
- ContainerCPPServer().run()
- #
- # Attente de la disponibilité du Container C++ local
- # dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
- #
- # Lancement Container Python local
- #
- if with_container_python:
- ContainerPYServer().run()
- #
- # Attente de la disponibilité du Container Python local
- # dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
-
- if with_container_superv:
- #
- # Lancement Container Supervision local
- #
- ContainerSUPERVServer().run()
- #
- # Attente de la disponibilité du Container Supervision local
+ #
+ # Lancement Session Loader
+ #
+ SessionLoader().run()
+
+ #
+ # Initialisation ORB et Naming Service
+ #
+ clt=orbmodule.client()
+
+ # (non obligatoire) Lancement Logger Server et attente de sa
+ # disponibilite dans le naming service
+ #
+ if with_logger:
+ LoggerServer().run()
+ clt.waitLogger("Logger")
+
+ #
+ # Lancement Registry Server
+ #
+ RegistryServer().run()
+
+ #
+ # Attente de la disponibilité du Registry dans le Naming Service
+ #
+ clt.waitNS("/Registry")
+
+ #
+ # Lancement Catalog Server
+ #
+ cataServer=CatalogServer()
+ cataServer.setpath(liste_modules)
+ cataServer.run()
+
+ #
+ # Attente de la disponibilité du Catalog Server dans le Naming Service
+ #
+ import SALOME_ModuleCatalog
+ clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
+
+ #
+ # Lancement SalomeDS Server
+ #
+ os.environ["CSF_PluginDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
+ os.environ["CSF_SALOMEDS_ResourcesDefaults"]=os.path.join(kernel_root_dir,"share","salome","resources")
+ SalomeDSServer().run()
+
+ if "GEOM" in liste_modules:
+ print("GEOM OCAF Resources")
+ os.environ["CSF_GEOMDS_ResourcesDefaults"]=os.path.join(modules_root_dir["GEOM"],"share","salome","resources")
+
+
+ #
+ # Attente de la disponibilité du SalomeDS dans le Naming Service
+ #
+ clt.waitNS("/myStudyManager")
+
+ #
+ # Lancement Session Server
+ #
+ SessionServer().run()
+
+ #
+ # Attente de la disponibilité du Session Server dans le Naming Service
+ #
+ import SALOME
+ session=clt.waitNS("/Kernel/Session",SALOME.Session)
+
+ #
+ # Lancement containers
+ #
+ theComputer = os.getenv("HOSTNAME")
+ theComputer = theComputer.split('.')[0]
+
+ #
+ # Lancement Container C++ local
+ #
+ if with_container_cpp:
+ ContainerCPPServer().run()
+ #
+ # Attente de la disponibilité du Container C++ local
# dans le Naming Service
- #
- clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
- #
- # Activation du GUI de Session Server
- #
- #session.GetInterface()
+ #
+ clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
+ #
+ # Lancement Container Python local
+ #
+ if with_container_python:
+ ContainerPYServer().run()
+ #
+ # Attente de la disponibilité du Container Python local
+ # dans le Naming Service
+ #
+ clt.waitNS("/Containers/" + theComputer + "/FactoryServerPy")
+
+ if with_container_superv:
+ #
+ # Lancement Container Supervision local
+ #
+ ContainerSUPERVServer().run()
+ #
+ # Attente de la disponibilité du Container Supervision local
+ # dans le Naming Service
+ #
+ clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
+ #
+ # Activation du GUI de Session Server
+ #
+ #session.GetInterface()
- end_time = os.times()
- print
- print "Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4])
+ end_time = os.times()
+ print()
+ print("Start SALOME, elpased time : %5.1f seconds"% (end_time[4] - init_time[4]))
- return clt
+ return clt
#
# -----------------------------------------------------------------------------
#
if __name__ == "__main__":
- clt=None
- try:
- clt = startSalome()
- except:
- print
- print
- print "--- erreur au lancement Salome ---"
-
- #print process_id
-
-
- filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
- #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
-
- fpid=open(filedict, 'w')
- pickle.dump(process_id,fpid)
- fpid.close()
-
- print """
-
-Sauvegarde du dictionnaire des process dans , %s
-Pour tuer les process SALOME, executer : python killSalome.py depuis
-une console, ou bien killSalome() depuis le present interpreteur,
-s'il n'est pas fermé.
-
-runSalome, avec l'option --killall, commence par tuer les process restants
-d'une execution précédente.
-
-Pour lancer uniquement le GUI, executer startGUI() depuis le present interpreteur,
-s'il n'est pas fermé.
-
-""" % filedict
-
- #
- # Impression arborescence Naming Service
- #
-
- if clt != None:
- print
- print " --- registered objects tree in Naming Service ---"
- clt.showNS()
- session=clt.waitNS("/Kernel/Session")
- catalog=clt.waitNS("/Kernel/ModulCatalog")
- import socket
- container = clt.waitNS("/Containers/" + socket.gethostname().split('.')[0] + "/FactoryServerPy")
-
- if os.path.isfile("~/.salome/pystartup"):
- f=open(os.path.expanduser("~/.salome/pystartup"),'w')
- PYTHONSTARTUP=f.read()
- f.close()
- else:
- PYTHONSTARTUP="""
-# Add auto-completion and a stored history file of commands to your Python
-# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
-# bound to the TAB key by default (you can change it - see readline docs).
-#
-# Store the history in ~/.salome/pyhistory,
-#
-import atexit
-import os
-import readline
-import rlcompleter
-readline.parse_and_bind('tab: complete')
+ clt=None
+ try:
+ clt = startSalome()
+ except:
+ print()
+ print()
+ print("--- erreur au lancement Salome ---")
+
+ #print process_id
+
+
+ filedict='/tmp/'+os.getenv('USER')+'_SALOME_pidict'
+ #filedict='/tmp/'+os.getlogin()+'_SALOME_pidict'
+
+ fpid=open(filedict, 'w')
+ pickle.dump(process_id,fpid)
+ fpid.close()
+
+ print("""
+
+ Sauvegarde du dictionnaire des process dans , %s
+ Pour tuer les process SALOME, executer : python killSalome.py depuis
+ une console, ou bien killSalome() depuis le present interpreteur,
+ s'il n'est pas fermé.
+
+ runSalome, avec l'option --killall, commence par tuer les process restants
+ d'une execution précédente.
+
+ Pour lancer uniquement le GUI, executer startGUI() depuis le present interpreteur,
+ s'il n'est pas fermé.
+
+ """ % filedict)
+
+ #
+ # Impression arborescence Naming Service
+ #
+
+ if clt != None:
+ print()
+ print(" --- registered objects tree in Naming Service ---")
+ clt.showNS()
+ session=clt.waitNS("/Kernel/Session")
+ catalog=clt.waitNS("/Kernel/ModulCatalog")
+ import socket
+ container = clt.waitNS("/Containers/" + socket.gethostname().split('.')[0] + "/FactoryServerPy")
+
+ if os.path.isfile("~/.salome/pystartup"):
+ f=open(os.path.expanduser("~/.salome/pystartup"),'w')
+ PYTHONSTARTUP=f.read()
+ f.close()
+ else:
+ PYTHONSTARTUP="""
+ # Add auto-completion and a stored history file of commands to your Python
+ # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
+ # bound to the TAB key by default (you can change it - see readline docs).
+ #
+ # Store the history in ~/.salome/pyhistory,
+ #
+ import atexit
+ import os
+ import readline
+ import rlcompleter
+ readline.parse_and_bind('tab: complete')
-historyPath = os.path.expanduser("~/.salome/pyhistory")
+ historyPath = os.path.expanduser("~/.salome/pyhistory")
-def save_history(historyPath=historyPath):
- import readline
- readline.write_history_file(historyPath)
+ def save_history(historyPath=historyPath):
+ import readline
+ readline.write_history_file(historyPath)
-if os.path.exists(historyPath):
- readline.read_history_file(historyPath)
+ if os.path.exists(historyPath):
+ readline.read_history_file(historyPath)
-atexit.register(save_history)
-del os, atexit, readline, rlcompleter, save_history, historyPath
-"""
- f=open(os.path.expanduser("~/.salome/pystartup"),'w')
- f.write(PYTHONSTARTUP)
- f.close()
+ atexit.register(save_history)
+ del os, atexit, readline, rlcompleter, save_history, historyPath
+ """
+ f=open(os.path.expanduser("~/.salome/pystartup"),'w')
+ f.write(PYTHONSTARTUP)
+ f.close()
- exec PYTHONSTARTUP in {}
-
+ exec(PYTHONSTARTUP, {})
files = '''$files'''
-print 'Byte-compiling python modules...'
+print('Byte-compiling python modules...')
for file in string.split(files):
$pathtrans
$filetrans
if not os.path.exists(filepath) or not (len(filepath) >= 3
and filepath[-3:] == '.py'):
- continue
- print file,
+ continue
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(filepath, filepath + 'c', path)
-print" || exit $?
+print()" || exit $?
# this will fail for python < 1.5, but that doesn't matter ...
$PYTHON -O -c "
import sys, os, string, py_compile
files = '''$files'''
-print 'Byte-compiling python modules (optimized versions) ...'
+print('Byte-compiling python modules (optimized versions) ...')
for file in string.split(files):
$pathtrans
$filetrans
if not os.path.exists(filepath) or not (len(filepath) >= 3
and filepath[-3:] == '.py'):
- continue
- print file,
+ continue
+ print(file, end='')
sys.stdout.flush()
py_compile.compile(filepath, filepath + 'o', path)
-print" 2>/dev/null || :
-
-# Local Variables:
-# mode: shell-script
-# sh-indentation: 2
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-end: "$"
-# End:
+print()" 2>/dev/null || :
+
msgstr "Ceci est un simple test"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::INF_HXX2SALOME_GENERIC_CLASS_NAME_CHECK"
-msgstr "Cochée"
+msgstr "Cochée"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::INF_HXX2SALOME_GENERIC_CLASS_NAME_UNCHECK"
-msgstr "Décochée"
+msgstr "Décochée"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::RES_HXX2SALOME_GENERIC_CLASS_NAME_TITLE"
msgstr "Dialogue example de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::RES_HXX2SALOME_GENERIC_CLASS_NAME_TEXT"
-msgstr "Les préférences sont : \n\tCase à cocher : %1\n\tEntier : %2\n\tEntier2 : %3\n\tDouble : %4\n\tTexte : %5"
+msgstr "Les préférences sont : \n\tCase à cocher : %1\n\tEntier : %2\n\tEntier2 : %3\n\tDouble : %4\n\tTexte : %5"
msgid "TLT_MY_NEW_ITEM"
-msgstr "Un article de menu propre à HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Un article de menu propre à HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_MY_NEW_ITEM"
msgstr "Mon menu"
msgid "STS_MY_NEW_ITEM"
-msgstr "Affiche une boîte de dialogue simple"
+msgstr "Affiche une boîte de dialogue simple"
msgid "TLT_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "STS_HXX2SALOME_GENERIC_CLASS_NAME_ACTION"
-msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
+msgstr "Ouvre la boîte de dialogue de HXX2SALOME_GENERIC_CLASS_NAME"
msgid "MEN_FILE"
msgstr "&File"
#-------------------------------------------------------------------------
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_TAB_GENERAL"
-msgstr "Général"
+msgstr "Général"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_GROUP_DEFAULTS"
-msgstr "Valeurs par défaut"
+msgstr "Valeurs par défaut"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_BOOL"
msgstr "Cochez-moi"
msgstr "Entrez un entier :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SPININT"
-msgstr "Cliquez sur les flèches (entier) :"
+msgstr "Cliquez sur les flèches (entier) :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SPINDBL"
-msgstr "Cliquez sur les flèches (double) :"
+msgstr "Cliquez sur les flèches (double) :"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_DEFAULT_SELECTOR"
msgstr "Choisissez une option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_0"
-msgstr "Première option"
+msgstr "Première option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_1"
msgstr "Seconde option"
msgid "HXX2SALOME_GENERIC_CLASS_NAMEGUI::PREF_LIST_TEXT_2"
-msgstr "Troisième option"
+msgstr "Troisième option"
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-mport salome
+import salome
import HXX2SALOME_GENERIC_CLASS_NAME_ORB
myHXX2SALOME_GENERIC_CLASS_NAME = salome.lcc.FindOrLoadComponent("FactoryServer", "HXX2SALOME_GENERIC_CLASS_NAME")
#
#
-print "Hello HXX2SALOME_GENERIC_CLASS_NAME"
+print("Hello HXX2SALOME_GENERIC_CLASS_NAME")
# Test here some of HXX2SALOME_GENERIC_CLASS_NAME methods ...
#
#
END {
-# CNC peut être mis dans le template directement printf "\nprivate:\n std::auto_ptr<%s> cppImpl_;\n",class_name >> hxx_file
+# CNC peut être mis dans le template directement printf "\nprivate:\n std::auto_ptr<%s> cppImpl_;\n",class_name >> hxx_file
}
# additional include directories
INCLUDE_DIRECTORIES(
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PYTHON_INCLUDE_DIR}
${PROJECT_SOURCE_DIR}/src/bases
${PROJECT_SOURCE_DIR}/src/engine
${CPPUNIT_INCLUDE_DIRS}
${PYTHON_INCLUDE_DIR}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${KERNEL_INCLUDE_DIRS}
${CMAKE_CURRENT_SOURCE_DIR}/..
${CMAKE_CURRENT_SOURCE_DIR}/../../bases
YACSLoader loader;
Executor executor;
-
try
{
p=loader.load(schema);
+
+ std::cerr << __FILE__ << std::endl;
DEBTRACE("Proc *p = " << p);
std::ofstream f("toto");
p->writeDot(f);
f.close();
DEBTRACE("+++++++++++++++++++ BEGIN execution " << schema);
+ std::cerr << __FILE__ << std::endl;
executor.RunW(p,0);
+ std::cerr << __FILE__ << std::endl;
+
DEBTRACE("+++++++++++++++++++ END execution " << schema);
std::ofstream g("titi");
p->writeDot(g);
catch (YACS::Exception& e)
{
DEBTRACE("YACS exception caught: ");
+ std::cerr << __FILE__ << std::endl;
DEBTRACE(e.what());
+ std::cerr << __FILE__ << std::endl;
+
DEBTRACE("+++++++++++++++++++ END test in error " << schema);
return 1;
}
catch (const std::ios_base::failure&)
{
+ std::cerr << __FILE__ << std::endl;
+
DEBTRACE("io failure");
+ std::cerr << __FILE__ << std::endl;
+
DEBTRACE("+++++++++++++++++++ END test in error " << schema);
return 1;
}
const char *p = tc->name();
if ( *p != '\0' )
{
+ std::cerr << __FILE__ << std::endl;
+
DEBTRACE(p);
}
else
{
+ std::cerr << __FILE__ << std::endl;
DEBTRACE(tc->id());
}
DEBTRACE("+++++++++++++++++++ END test in error " << schema);
if (p)
{
PyObject *data = ((OutputPyPort*)p->nodeMap["node2"]->getOutputPort("p1"))->get();
- char *text = PyString_AsString(data);
+ char *text = PyBytes_AsString(data);
CPPUNIT_ASSERT_EQUAL(string("coucoucoucoucoucoucoucou"), string(text));
delete p;
}
if (p)
{
PyObject *data = ((OutputPyPort*)p->nodeMap["node2"]->getOutputPort("p1"))->get();
- char *text = PyString_AsString(data);;
+ char *text = PyBytes_AsString(data);;
CPPUNIT_ASSERT_EQUAL(string("coucoucoucoucoucoucoucou"), string(text) );
delete p;
}
"""Optional method called on initialization.
The type of "input" is returned by "getTCForAlgoInit"
"""
- print "Algo initialize, input = ", input.getIntValue()
+ print("Algo initialize, input = ", input.getIntValue())
def startToTakeDecision(self):
"""This method is called only once to launch the algorithm. It must
pool, do nothing (wait for more samples), or empty the pool and
return to finish the evaluation.
"""
- print "startToTakeDecision"
+ print("startToTakeDecision")
# fill the pool with samples
iter=0
self.pool.pushInSample(0, 0.5)
currentId=self.pool.getCurrentId()
valIn = self.pool.getCurrentInSample().getDoubleValue()
valOut = self.pool.getCurrentOutSample().getIntValue()
- print "Compute currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut)
+ print("Compute currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut))
iter=iter+1
if iter < 3:
def finish(self):
"""Optional method called when the algorithm has finished, successfully
or not, to perform any necessary clean up."""
- print "Algo finish"
+ print("Algo finish")
self.pool.destroyAll()
def getAlgoResult(self):
"""Optional method called on initialization.
The type of "input" is returned by "getTCForAlgoInit"
"""
- print "Algo initialize, input = ", input.getIntValue()
+ print("Algo initialize, input = ", input.getIntValue())
def start(self):
"""Start to fill the pool with samples to evaluate."""
- print "Algo start "
+ print("Algo start ")
self.iter=0
# pushInSample(id, value)
self.pool.pushInSample(self.iter, 0.5)
currentId=self.pool.getCurrentId()
valIn = self.pool.getCurrentInSample().getDoubleValue()
valOut = self.pool.getCurrentOutSample().getIntValue()
- print "Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut)
+ print("Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut))
self.iter=self.iter+1
if self.iter < 3:
def finish(self):
"""Optional method called when the algorithm has finished, successfully
or not, to perform any necessary clean up."""
- print "Algo finish"
+ print("Algo finish")
self.pool.destroyAll()
def getAlgoResult(self):
rootContext = obj._narrow(CosNaming.NamingContext)
if rootContext is None:
- print "Failed to narrow the root naming context"
+ print("Failed to narrow the root naming context")
sys.exit(1)
# Resolve the name "test.my_context/Echo.Object"
try:
obj = rootContext.resolve(name)
-except CosNaming.NamingContext.NotFound, ex:
- print "Name not found"
+except CosNaming.NamingContext.NotFound as ex:
+ print("Name not found")
sys.exit(1)
# Narrow the object to an eo::Echo
echo = obj._narrow(eo.Echo)
if echo is None:
- print "Object reference is not an eo::Echo"
+ print("Object reference is not an eo::Echo")
sys.exit(1)
# Invoke the echoString operation
message = "Hello from Python"
result = echo.echoString(message)
-print "I said '%s'. The object said '%s'." % (message,result)
+print("I said '%s'. The object said '%s'." % (message,result))
"""
struct S1
s2=eo.S2(s1)
r=echo.echoStruct(s2)
-print r
+print(r)
s3=eo.S3(x=1,y=2,s="aa",b=True,ob=None)
r=echo.echoStruct2(s3)
-print r
+print(r)
ob=echo.createObj(3)
-print ob
+print(ob)
oc=echo.createC()
-print oc
+print(oc)
s3=eo.S3(x=1,y=2,s="aa",b=True,ob=ob)
r=echo.echoStruct2(s3)
-print r
+print(r)
s3=eo.S3(x=1,y=2,s="aa",b=True,ob=oc)
r=echo.echoStruct2(s3)
-print r
+print(r)
r=echo.echoObjectVec([ob,ob])
-print r
+print(r)
r=echo.echoObjectVec([oc,oc])
-print r
+print(r)
r=echo.echoObjectVec([ob,oc])
-print r
+print(r)
#echo.shutdown()
The last node gives the sum of rank n (=2**n) and also a direct calculation of 2**n.
"""
- print """
+ print("""
<proc>
<!-- types -->
<!-- inline -->
<inline name="node_0_0" >
<script><code>
import time
-from decimal import *"""
- print "getcontext().prec = " + str(1+n/3)
- print """
+from decimal import *""")
+ print("getcontext().prec = " + str(1+n/3))
+ print("""
aa=Decimal(a)
bb=Decimal(b)
cc=aa+bb
c=str(cc)
-print "cc=",cc
+print("cc=",cc)
time.sleep(1)
</code></script>
<inport name="a" type="string"/>
<inport name="b" type="string"/>
<outport name="c" type="string"/>
-</inline>"""
+</inline>""")
- print """
+ print("""
<inline name="collect" >
-<script><code>"""
- print "import time"
- print "from decimal import *"
- print "getcontext().prec = " + str(1+n/3)
- print "tot = Decimal(0)"
- print "for i in range (" + str(n+1) + "):"
- print " v='a' + str(i)"
- print " tot+=Decimal(eval(v))"
- print "print tot"
- print "result=str(tot)"
- print "ref=Decimal(2)**" + str(n)
- print "reference=str(ref)"
- print "time.sleep(1)"
- print "</code></script>"
+<script><code>""")
+ print("import time")
+ print("from decimal import *")
+ print("getcontext().prec = " + str(1+n/3))
+ print("tot = Decimal(0)")
+ print("for i in range (" + str(n+1) + "):")
+ print(" v='a' + str(i)")
+ print(" tot+=Decimal(eval(v))")
+ print("print(tot)")
+ print("result=str(tot)")
+ print("ref=Decimal(2)**" + str(n))
+ print("reference=str(ref)")
+ print("time.sleep(1)")
+ print("</code></script>")
for i in range (n+1):
inport='<inport name="a' + str(i) + '" type="string"/>'
- print inport
+ print(inport)
pass
- print '<outport name="result" type="string"/>'
- print '<outport name="reference" type="string"/>'
- print "</inline>"
- print
+ print('<outport name="result" type="string"/>')
+ print('<outport name="reference" type="string"/>')
+ print("</inline>")
+ print()
for i in range (1,n+1):
for j in range (i+1):
node="node_" + str(i) +"_" + str(j)
nodetxt='<node name="'+node+'" type="node_0_0"></node>'
- print nodetxt
+ print(nodetxt)
pass
pass
- print """
+ print("""
<!-- service -->
<!-- control -->
- """
+ """)
for i in range (n):
for j in range (i+1):
tonode2="node_" + str(i+1) +"_" + str(j+1)
control1='<control> <fromnode>'+fromnode+'</fromnode> <tonode>'+tonode1+'</tonode> </control>'
control2='<control> <fromnode>'+fromnode+'</fromnode> <tonode>'+tonode2+'</tonode> </control>'
- print control1
- print control2
+ print(control1)
+ print(control2)
pass
pass
for i in range (n+1):
fromnode="node_" + str(n) +"_" + str(i)
control='<control> <fromnode>'+fromnode+'</fromnode> <tonode>collect</tonode> </control>'
- print control
+ print(control)
pass
- print """
+ print("""
<!-- datalinks -->
- """
+ """)
for i in range (n):
for j in range (i+1):
datafrom='<fromnode>' + fromnode + '</fromnode> <fromport>c</fromport>'
datato1 ='<tonode>' + tonode1 + '</tonode> <toport>b</toport>'
datato2 ='<tonode>' + tonode2 + '</tonode> <toport>a</toport>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato1
- print '</datalink>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato2
- print '</datalink>'
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato1)
+ print('</datalink>')
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato2)
+ print('</datalink>')
pass
pass
for i in range (n+1):
datafrom='<fromnode>' + fromnode + '</fromnode> <fromport>c</fromport>'
toport='a' + str(i)
datato ='<tonode>collect</tonode> <toport>' + toport + '</toport>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato
- print '</datalink>'
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato)
+ print('</datalink>')
- print """
+ print("""
<!--parameters -->
- """
+ """)
- print """
+ print("""
<parameter>
<tonode>node_0_0</tonode> <toport>a</toport>
<value><string>0</string></value>
<tonode>node_0_0</tonode> <toport>b</toport>
<value><string>1</string></value>
</parameter>
- """
+ """)
for i in range (1,n+1):
node1="node_" + str(i) +"_" + str(0)
node2="node_" + str(i) +"_" + str(i)
tonode1 =' <tonode>' + node1 + '</tonode> <toport>a</toport>'
tonode2 =' <tonode>' + node2 + '</tonode> <toport>b</toport>'
- print '<parameter>'
- print tonode1
- print ' <value><string>0</string></value>'
- print '</parameter>'
+ print('<parameter>')
+ print(tonode1)
+ print(' <value><string>0</string></value>')
+ print('</parameter>')
- print '<parameter>'
- print tonode2
- print ' <value><string>0</string></value>'
- print '</parameter>'
+ print('<parameter>')
+ print(tonode2)
+ print(' <value><string>0</string></value>')
+ print('</parameter>')
- print """
+ print("""
</proc>
- """
+ """)
if __name__ == "__main__":
import sys
if rank <2:
raise ValueError("rank must be >1")
except (IndexError, ValueError):
- print usage%(sys.argv[0])
+ print(usage%(sys.argv[0]))
sys.exit(1)
pass
triangle(rank)
<inline name="node_0_0" >
<script><code>
c=a+b
-print c
+print(c)
</code></script>
<inport name="a" type="int"/>
<inport name="b" type="int"/>
The last node gives the sum of rank n (=2**n) and also a direct calculation of 2**n.
"""
- print debut
+ print(debut)
- print """
+ print("""
<inline name="collect" >
-<script><code>"""
- print "tot = 0"
- print "for i in range (" + str(n+1) + "):"
- print " v='a' + str(i)"
- print " tot+=eval(v)"
- print "result=tot"
- print "print result"
- print "reference=2**" + str(n)
- print "print reference"
- print "</code></script>"
+<script><code>""")
+ print("tot = 0")
+ print("for i in range (" + str(n+1) + "):")
+ print(" v='a' + str(i)")
+ print(" tot+=eval(v)")
+ print("result=tot")
+ print("print result")
+ print("reference=2**" + str(n))
+ print("print reference")
+ print("</code></script>")
for i in range (n+1):
inport='<inport name="a' + str(i) + '" type="int"/>'
- print inport
+ print(inport)
pass
- print '<outport name="result" type="int"/>'
- print '<outport name="reference" type="int"/>'
- print "</inline>"
- print
+ print('<outport name="result" type="int"/>')
+ print('<outport name="reference" type="int"/>')
+ print("</inline>")
+ print()
for i in range (1,n+1):
for j in range (i+1):
node="node_" + str(i) +"_" + str(j)
nodetxt='<node name="'+node+'" type="node_0_0"></node>'
- print nodetxt
+ print(nodetxt)
pass
pass
- print """
+ print("""
<!-- service -->
<!-- control -->
- """
+ """)
for i in range (n):
for j in range (i+1):
tonode2="node_" + str(i+1) +"_" + str(j+1)
control1='<control> <fromnode>'+fromnode+'</fromnode> <tonode>'+tonode1+'</tonode> </control>'
control2='<control> <fromnode>'+fromnode+'</fromnode> <tonode>'+tonode2+'</tonode> </control>'
- print control1
- print control2
+ print(control1)
+ print(control2)
pass
pass
- print """
+ print("""
<!-- datalinks -->
- """
+ """)
for i in range (n):
for j in range (i+1):
datafrom='<fromnode>' + fromnode + '</fromnode> <fromport>c</fromport>'
datato1 ='<tonode>' + tonode1 + '</tonode> <toport>b</toport>'
datato2 ='<tonode>' + tonode2 + '</tonode> <toport>a</toport>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato1
- print '</datalink>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato2
- print '</datalink>'
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato1)
+ print('</datalink>')
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato2)
+ print('</datalink>')
pass
pass
datafrom='<fromnode>' + fromnode + '</fromnode> <fromport>c</fromport>'
toport='a' + str(i)
datato ='<tonode>collect</tonode> <toport>' + toport + '</toport>'
- print '<datalink>'
- print ' ' + datafrom
- print ' ' + datato
- print '</datalink>'
+ print('<datalink>')
+ print(' ' + datafrom)
+ print(' ' + datato)
+ print('</datalink>')
- print """
+ print("""
<!--parameters -->
- """
+ """)
- print """
+ print("""
<parameter>
<tonode>node_0_0</tonode> <toport>a</toport>
<value><int>0</int></value>
<tonode>node_0_0</tonode> <toport>b</toport>
<value><int>1</int></value>
</parameter>
- """
+ """)
for i in range (1,n+1):
node1="node_" + str(i) +"_" + str(0)
node2="node_" + str(i) +"_" + str(i)
tonode1 =' <tonode>' + node1 + '</tonode> <toport>a</toport>'
tonode2 =' <tonode>' + node2 + '</tonode> <toport>b</toport>'
- print '<parameter>'
- print tonode1
- print ' <value><int>0</int></value>'
- print '</parameter>'
+ print('<parameter>')
+ print(tonode1)
+ print(' <value><int>0</int></value>')
+ print('</parameter>')
- print '<parameter>'
- print tonode2
- print ' <value><int>0</int></value>'
- print '</parameter>'
+ print('<parameter>')
+ print(tonode2)
+ print(' <value><int>0</int></value>')
+ print('</parameter>')
- print """
+ print("""
</proc>
- """
+ """)
if __name__ == "__main__":
import sys
if rank >31:
raise ValueError("rank must be <32")
except (IndexError, ValueError):
- print usage%(sys.argv[0])
+ print(usage%(sys.argv[0]))
sys.exit(1)
pass
triangle(rank)
"""Optional method called on initialization.
The type of "input" is returned by "getTCForAlgoInit"
"""
- print "Algo initialize, input = ", input.getIntValue()
+ print("Algo initialize, input = ", input.getIntValue())
def start(self):
"""Start to fill the pool with samples to evaluate."""
- print "Algo start "
+ print("Algo start ")
self.iter=0
# pushInSample(id, value)
self.pool.pushInSample(self.iter, 1)
currentId=self.pool.getCurrentId()
valIn = self.pool.getCurrentInSample().getIntValue()
valOut = self.pool.getCurrentOutSample().getIntValue()
- print "Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut)
+ print("Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut))
self.iter=self.iter+1
if self.iter < 3:
def finish(self):
"""Optional method called when the algorithm has finished, successfully
or not, to perform any necessary clean up."""
- print "Algo finish"
+ print("Algo finish")
self.pool.destroyAll()
def getAlgoResult(self):
import os
import orbmodule
-import salome_utils
+import salome_utils
clt = orbmodule.client()
FactoryContainer = "/Containers/" + salome_utils.getShortHostName() + "/FactoryServer"
clt.waitNS(FactoryContainer)
-
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import xmlrpclib,sys
+import xmlrpc.client,sys
#example
data="""
</methodCall>
"""
def echo(args):
- print "args=",args
+ print("args=",args)
if not args:
return None
elif len(args) == 1:
f=open("input")
data=f.read()
f.close()
-print data
+print(data)
class Objref:
"""Wrapper for objrefs """
out.write(self.data or "")
out.write("</objref></value>\n")
-xmlrpclib.WRAPPERS=xmlrpclib.WRAPPERS+(Objref,)
+xmlrpc.client.WRAPPERS=xmlrpc.client.WRAPPERS+(Objref,)
def end_objref(self,data):
self.append(Objref(data))
self._value=0
-xmlrpclib.Unmarshaller.end_objref=end_objref
-xmlrpclib.Unmarshaller.dispatch["objref"]=end_objref
+xmlrpc.client.Unmarshaller.end_objref=end_objref
+xmlrpc.client.Unmarshaller.dispatch["objref"]=end_objref
-params, method = xmlrpclib.loads(data)
+params, method = xmlrpc.client.loads(data)
try:
call=eval(method)
response = (response,)
except:
# report exception back to server
- response = xmlrpclib.dumps( xmlrpclib.Fault(1, "%s:%s" % sys.exc_info()[:2]))
+ response = xmlrpc.client.dumps( xmlrpc.client.Fault(1, "%s:%s" % sys.exc_info()[:2]))
else:
- response = xmlrpclib.dumps( response, methodresponse=1)
+ response = xmlrpc.client.dumps( response, methodresponse=1)
-print response
+print(response)
f=open("output",'w')
f.write(response)
f.close()
{
XML_SetUserData(saxContext,pp);
_stackParser.push(pp);
- DEBTRACE("parser::SetUserDataAndPush, stack size: " << sp.size());
+ DEBTRACE("parser::SetUserDataAndPush, stack size: " << pp->_level);
}
void parser::onEnd(const XML_Char *el, parser* child)
INCLUDE_DIRECTORIES(
${CPPUNIT_INCLUDE_DIRS}
${PTHREADS_INCLUDE_DIRS}
+ ${OMNIORBPY_INCLUDE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/
${CMAKE_CURRENT_SOURCE_DIR}/..
${CMAKE_CURRENT_SOURCE_DIR}/../../bases
<inline name="node98" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="objvec"/>
</inline>
<inline name="node1" state="disabled">
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="int"/>
</inline>
<inline name="node11" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="string"/>
</inline>
<inline name="node12" >
<script>
- <code>print p1</code>
- <code>print "coucou"</code>
+ <code>print(p1)</code>
+ <code>print("coucou")</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<inline name="node13" >
<script>
- <code><![CDATA[print p1]]></code>
- <code><![CDATA[print "coucou"]]> </code>
+ <code><![CDATA[print(p1)]]></code>
+ <code><![CDATA[print("coucou")]]> </code>
<code><![CDATA[a=1/0]]> </code>
</script>
<inport name="p1" type="dblevecvec"/>
<script>
<code>import eo</code>
<code>obj=obj._narrow(eo.Echo)</code>
- <code>print p1</code>
- <code>print obj</code>
+ <code>print(p1)</code>
+ <code>print(obj)</code>
<code>p2=obj.echoC(p1)</code>
- <code>print p2</code>
+ <code>print(p2)</code>
</script>
<inport name="p1" type="eo/C"/>
<inport name="obj" type="Echo"/>
</inline>
<inline name="node34" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="eo/C"/>
<outport name="p2" type="eo/C"/>
</inline>
<inline name="node35" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="eo/C"/>
<outport name="p2" type="eo/C"/>
<inline name="node1" >
<function name="f">
<code>def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
+ <code> print(p1);p1=2*p1 </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<inline name="node1" >
<function name="f">
<code>def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
+ <code> print(p1);p1=2*p1 </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<inline name="node1" >
<function name="f">
<code>def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
- <code> print "coucou b1.b2.node1" </code>
+ <code> print(p1);p1=2*p1 </code>
+ <code> print("coucou b1.b2.node1") </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<inline name="node1" >
<function name="f">
<code> def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
+ <code> print(p1);p1=2*p1 </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<inline name="node2" >
<function name="f">
<code>def f(s1):</code>
- <code> print s1 </code>
+ <code> print(s1) </code>
<code> return s1 </code>
</function>
<inport name="s1" type="dblevec"/>
<inline name="node1" >
<function name="f">
<code>def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
+ <code> print(p1);p1=2*p1 </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<inline name="pyth5" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="boolvec"/>
<outport name="p1" type="boolvec"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="boolvec"/>
<outport name="p1" type="boolvec"/>
<inline name="pyth1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<inline name="pyth2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<inline name="pyth3" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<inline name="pyth4" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</foreach>
<inline name="pyth5" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
<outport name="p1" type="dblevec"/>
</datanode>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<bloc name="b">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<inline name="pyth5" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
<outport name="p1" type="dblevec"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
<outport name="p1" type="dblevec"/>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<outport name="p1" type="string"/>
</inline>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
<code>#a=1/0</code>
</script>
<outport name="p1" type="string"/>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<outport name="p1" type="string"/>
</inline>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
<code>#a=1/0</code>
</script>
<inport name="p1" type="string"/>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<outport name="p1" type="string"/>
</inline>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
<code>a=1/0</code>
</script>
<outport name="p1" type="string"/>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<!-- service -->
<inline name="node1" >
- <script><code>print p1;p1=2*p1</code></script>
+ <script><code>print(p1);p1=2*p1</code></script>
<inport name="p1" type="string"/>
<outport name="p1" type="string"/>
</inline>
<inline name="node0" >
<script>
<code>p1="toto"</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<outport name="p1" type="string"/>
</inline>
<inline name="node3" >
<script>
- <code>print "node3:",p1</code>
+ <code>print("node3:",p1)</code>
</script>
<inport name="p1" type="file"/>
</inline>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
</bloc>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
</inline>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
</foreach>
<inline name="node3" >
<script>
- <code>print "coucou"</code>
+ <code>print("coucou")</code>
</script>
</inline>
<service name="node4" >
</bloc>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="intvecvec"/>
<outport name="p1" type="intvecvec"/>
</inline>
<inline name="node3" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="intvecvec"/>
</inline>
runs[run].append(medFile)
runs[run].append(meshName)
pass
-print "There is(are) ",numberOfRun," runs of Fake Compo on process ",os.getpid()
+print("There is(are) ",numberOfRun," runs of Fake Compo on process ",os.getpid())
]]></code></script>
<outport name="numberOfRun" type="int"/>
<outport name="runs" type="seqpyobj"/>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<function name="f">
<code>import time</code>
<code>def f(p1):</code>
- <code> print "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ start ", p1</code>
+ <code> print("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ start ", p1)</code>
<code> time.sleep(0.1)</code>
- <code> print "----------------------------------------- stop ", p1</code>
+ <code> print("----------------------------------------- stop ", p1)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<foreach name="ForEachLoop" nbranch="4" type="int">
<initnode>
<inline name="initScript">
- <script><code><![CDATA[print "initnode"
+ <script><code><![CDATA[print("initnode")
o1=7
]]></code></script>
<outport name="o1" type="int"/>
</inline>
<finalizenode>
<inline name="finalizeScript">
- <script><code><![CDATA[print "finalizenode"
+ <script><code><![CDATA[print("finalizenode")
]]></code></script>
<inport name="i2" type="int"/>
</inline>
</datalink>
</foreach>
<inline name="PostProc">
- <script><code><![CDATA[print "Post-traitement"
+ <script><code><![CDATA[print("Post-traitement")
for x in i5:
- print x
+ print(x)
]]></code></script>
<load container="DefaultContainer"/>
<inport name="i5" type="seqint"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print "a=",a</code>
+ <code> print("a=",a)</code>
<code> a=a+p1</code>
- <code> print "a=",a</code>
+ <code> print("a=",a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print "a:",a</code>
+ <code> print("a:",a)</code>
<code> a=a+p1</code>
- <code> print "p1:",p1</code>
+ <code> print("p1:",p1)</code>
<code><![CDATA[ condition=(p1 < 40.)]]> </code>
<code> return p1,condition</code>
</function>
<inline name="node1" >
<function name="f">
<code>def f(p1):</code>
- <code> print p1;p1=2*p1 </code>
+ <code> print(p1);p1=2*p1 </code>
<code> return p1 </code>
</function>
<inport name="p1" type="string"/>
<script>
<code>import SALOME_MED</code>
<code>p1=p1._narrow(SALOME_MED.FIELD)</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="FIELDDOUBLE"/>
<outport name="p1" type="FIELDDOUBLE"/>
<inline name="pyth0" >
<script>
- <code>print "MEDFIELD:",p1</code>
+ <code>print (MEDFIELD:",p1)</code>
<code>p1.Register()</code>
</script>
<inport name="p1" type="FIELDDOUBLE"/>
<inline name="pyth1" >
<script>
- <code>print "MEDFIELD:",p1</code>
+ <code>print("MEDFIELD:",p1)</code>
</script>
<inport name="p1" type="FIELDDOUBLE"/>
</inline>
<inline name="pyth5" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="intvec"/>
<outport name="p1" type="intvec"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="intvec"/>
<outport name="p1" type="intvec"/>
<inline name="poly_7" >
<script>
<code>Pn=(429*x**7 -693*x**5+315*x**3 -35*x)/16</code>
- <code>print "reference P7=",Pn</code>
+ <code>print("reference P7=",Pn)</code>
</script>
<inport name="x" type="double"/>
<outport name="Pn" type="double"/>
<inline name="iter1" >
<script>
<code>Pn = ((2*n-1)*x*Pnm1 -(n-1)*Pnm2)/n</code>
- <code>print "n=",n," Pn=",Pn</code>
+ <code>print("n=",n," Pn=",Pn)</code>
<code>n=n+1</code>
</script>
<inport name="Pnm1" type="double"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="objvec"/>
<outport name="p1" type="objvec"/>
<foreach name="foreach4" nbranch="3" type="Obj" >
<inline name="pyth" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="Obj"/>
<outport name="p1" type="Obj"/>
<inline name="pyth7" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="objvec"/>
<outport name="p1" type="objvec"/>
<inline name="pyth0" >
<script>
- <code>print "p1",p1</code>
- <code>print "p2",p2</code>
+ <code>print("p1",p1)</code>
+ <code>print("p2",p2)</code>
<code>p1=[p1,p2,p2,p1]</code>
</script>
<inport name="p1" type="Obj"/>
<inline name="node2" >
<script >
<code>p1= p1+10.</code>
- <code>print "node2:",p1</code>
+ <code>print("node2:",p1)</code>
<code>#a=p1/0</code>
<code>p1=5</code>
</script>
<inline name="node2" >
<script >
<code>p1= p1+10.</code>
- <code>print "node2:",p1</code>
+ <code>print("node2:",p1)</code>
<code>#a=p1/0</code>
<code>p1=5</code>
</script>
<optimizer name="OptimizerLoop1" nbranch="1" lib="libTestOptLoop" entry="createOptimizerAlgASyncExample">
<inline name="PyScript7">
<script><code><![CDATA[o9 = int(i8)
-print "traitement:", i8
+print("traitement:", i8)
]]></code></script>
<load container="DefaultContainer"/>
<inport name="i8" type="double"/>
<optimizer name="OptimizerLoop1" nbranch="1" lib="algoasyncexample.py" entry="myalgoasync">
<inline name="PyScript7">
<script><code><![CDATA[o9 = int(i8)
-print "traitement:", i8
+print("traitement:", i8)
]]></code></script>
<load container="DefaultContainer"/>
<inport name="i8" type="double"/>
<optimizer name="OptimizerLoop1" nbranch="1" lib="libTestOptLoop" entry="createOptimizerAlgSyncExample">
<inline name="PyScript7">
<script><code><![CDATA[o9 = int(i8)
-print "traitement:", i8
+print("traitement:", i8)
]]></code></script>
<load container="DefaultContainer"/>
<inport name="i8" type="double"/>
<optimizer name="OptimizerLoop1" nbranch="1" lib="algosyncexample.py" entry="myalgosync">
<inline name="PyScript7">
<script><code><![CDATA[o9 = int(i8)
-print "traitement:", i8
+print("traitement:", i8)
]]></code></script>
<load container="DefaultContainer"/>
<inport name="i8" type="double"/>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="int"/>
</inline>
<inline name="node11" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="string"/>
</inline>
<inline name="node12" >
<script>
- <code>print p1</code>
- <code>print "coucou"</code>
+ <code>print(p1)</code>
+ <code>print("coucou")</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<inline name="node13" >
<script>
- <code><![CDATA[print p1]]></code>
- <code><![CDATA[print "coucou"]]> </code>
+ <code><![CDATA[print(p1)]]></code>
+ <code><![CDATA[print("coucou")]]> </code>
</script>
<inport name="p1" type="dblevecvec"/>
<outport name="p1" type="dblevecvec"/>
<script>
<code>import eo</code>
<code>obj=obj._narrow(eo.Echo)</code>
- <code>print p1</code>
- <code>print obj</code>
+ <code>print(p1)</code>
+ <code>print(obj)</code>
<code>p2=obj.echoC(p1)</code>
- <code>print p2</code>
+ <code>print(p2)</code>
</script>
<inport name="p1" type="C"/>
<inport name="obj" type="Echo"/>
</inline>
<inline name="node34" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="C"/>
<outport name="p2" type="C"/>
</inline>
<inline name="node35" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="C"/>
<outport name="p2" type="C"/>
<function name="ff2">
<code><![CDATA[
def ff2(x,a):
- print "coucou, x=",x
- print "coucou, a=",a
- print my_container
+ print("coucou, x=",x)
+ print("coucou, a=",a)
+ print(my_container)
return x+" OK ca marche"+str(a),2*a+4.7
]]></code>
</function>
</remote>
<inline name="node2">
<script><code><![CDATA[
-print "dans node2 p1=",p1
-print "dans node2 p2=",p2
+print("dans node2 p1=",p1)
+print("dans node2 p2=",p2)
]]></code></script>
<inport name="p1" type="string"/>
<inport name="p2" type="double"/>
<code><![CDATA[import time
def f():
- print my_container
- for n in xrange(15):
- print time.time()
+ print(my_container)
+ for n in range(15):
+ print(time.time())
time.sleep(1)
]]></code>
<function name="f">
<code><![CDATA[import time
def f():
- print my_container
- for n in xrange(15):
- print time.time()
+ print(my_container)
+ for n in range(15):
+ print(time.time())
time.sleep(1)
]]></code>
</function>
<code><![CDATA[import time
def f(i5):
- print my_container
- print "nouvelle branche avec ", i5
- for n in xrange(15):
- print time.time()
+ print(my_container)
+ print("nouvelle branche avec ", i5)
+ for n in range(15):
+ print(time.time())
time.sleep(1)
]]></code>
<remote name="Node6">
<script>
<code><![CDATA[
-print "coucou, x=",x
-print "coucou, a=",a
-print "my_container=",my_container
+print("coucou, x=",x)
+print("coucou, a=",a)
+print("my_container=",my_container)
y= x+" OK ca marche"+str(a)
z=2*a+4.7
-print y,z
+print(y,z)
]]></code>
</script>
<load container="cont1"/>
</remote>
<inline name="node2">
<script><code><![CDATA[
-print "dans node2 p1=",p1
-print "dans node2 p2=",p2
+print("dans node2 p1=",p1)
+print("dans node2 p2=",p2)
]]></code></script>
<inport name="p1" type="string"/>
<inport name="p2" type="double"/>
<code>def f(p1):</code>
<code> global a</code>
<code> a=a+1</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> return p1</code>
</function>
<inport name="p1" type="int"/>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="int"/>
</inline>
<inline name="node11" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="string"/>
</inline>
<inline name="node12" >
<script>
- <code>print p1</code>
- <code>print "coucou"</code>
+ <code>print(p1)</code>
+ <code>print("coucou")</code>
</script>
<inport name="p1" type="dblevec"/>
</inline>
<inline name="node13" >
<script>
- <code><![CDATA[print p1]]></code>
- <code><![CDATA[print "coucou"]]> </code>
+ <code><![CDATA[print(p1)]]></code>
+ <code><![CDATA[print("coucou")]]> </code>
</script>
<inport name="p1" type="dblevecvec"/>
<outport name="p1" type="dblevecvec"/>
<script>
<code>import eo</code>
<code>obj=obj._narrow(eo.Echo)</code>
- <code>print p1</code>
- <code>print obj</code>
+ <code>print(p1)</code>
+ <code>print(obj)</code>
<code>p2=obj.echoC(p1)</code>
- <code>print p2</code>
+ <code>print(p2)</code>
</script>
<inport name="p1" type="C"/>
<inport name="obj" type="Echo"/>
</inline>
<inline name="node34" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="C"/>
<outport name="p2" type="C"/>
</inline>
<inline name="node35" >
<script>
- <code>print p1;p2=p1</code>
+ <code>print(p1);p2=p1</code>
</script>
<inport name="p1" type="C"/>
<outport name="p2" type="C"/>
msg += "refOutput - output : %f - %f \n"%(refOutput, output);
msg += "Got abs relative diff %f .\n"%err
ret = False;
- print msg;
+ print(msg)
pass
-#print "+++ OK " , i , " +++", ret
+#print("+++ OK " , i , " +++", ret)
]]></code></script>
<inport name="i" type="int"/>
<inport name="refOutputs" type="pyobj"/>
<inline name="PyBuildLoopIndex">
<function name="make_indexes">
<code><![CDATA[def make_indexes(inVal, outVal) :
- print "In make_indexes" ;
+ print("In make_indexes")
if ( len(inVal) != len(outVal) ) :
msg = "len(inVal) (%i) != len(outVal) (%i). "%( len(inVal), len(outVal) ) ;
raise ValueError(msg)
<outport name="filepath" type="string"/>
</inline>
<inline name="PyGetRes">
- <script><code><![CDATA[print "retVec ";
-print retVec;
+ <script><code><![CDATA[print("retVec ");
+print(retVec);
res = "True";
for ret in retVec:
if not ret:
if errLR > epsilon or errANN > epsilon:
msg += "KO valid with eps %f at pattern #%i: \n"%(epsilon, i) ;
ret = False;
- print msg;
+ print(msg);
pass
-print "+++ OK " , i , " +++", ret
+print("+++ OK " , i , " +++", ret)
]]></code></script>
<inport name="i" type="int"/>
<inport name="refOutputsLR" type="pyobj"/>
<inline name="PyBuildLoopIndex0">
<function name="make_indexes">
<code><![CDATA[def make_indexes(inVal, outVal_LR, outVal_ANN) :
- print "In make_indexes" ;
+ print("In make_indexes") ;
if ( len(inVal) != len(outVal_LR) ) :
msg = "len(inVal) (%i) != len(outVal_LR) (%i). "%( len(inVal), len(outVal_LR) ) ;
<outport name="filepath" type="string"/>
</inline>
<inline name="PyGetRes">
- <script><code><![CDATA[print "retVec ";
-print retVec;
+ <script><code><![CDATA[print("retVec ");
+print(retVec);
res = "True";
for ret in retVec:
if not ret:
msg += "refOutput - output : %f - %f \n"%(refOutput, output);
msg += "Got abs relative diff %f .\n"%err
ret = False;
- print msg;
+ print(msg);
pass
-#print "+++ OK " , i , " +++", ret
+#print("+++ OK " , i , " +++", ret)
]]></code></script>
<inport name="i" type="int"/>
<inport name="refOutputs" type="pyobj"/>
<inline name="PyBuildLoopIndex">
<function name="make_indexes">
<code><![CDATA[def make_indexes(inVal, outVal) :
- print "In make_indexes" ;
+ print("In make_indexes") ;
if ( len(inVal) != len(outVal) ) :
msg = "len(inVal) (%i) != len(outVal) (%i). "%( len(inVal), len(outVal) ) ;
raise ValueError(msg)
<outport name="filepath" type="string"/>
</inline>
<inline name="PyGetRes">
- <script><code><![CDATA[print "retVec ";
-print retVec;
+ <script><code><![CDATA[print("retVec ");
+print(retVec);
res = "True";
for ret in retVec:
if not ret:
msg += "refOutput - output : %f - %f \n"%(refOutput, output);
msg += "Got abs relative diff %f .\n"%err
ret = False;
- print msg;
+ print(msg);
pass
-print "+++ OK " , i , " +++", ret
+print("+++ OK " , i , " +++", ret)
]]></code></script>
<inport name="i" type="int"/>
<inport name="refOutputs" type="pyobj"/>
<inline name="PyBuildLoopIndex">
<function name="make_indexes">
<code><![CDATA[def make_indexes(inVal, outVal) :
- print "In make_indexes" ;
+ print("In make_indexes") ;
if ( len(inVal) != len(outVal) ) :
msg = "len(inVal) (%i) != len(outVal) (%i). "%( len(inVal), len(outVal) ) ;
raise ValueError(msg)
<outport name="filepath" type="string"/>
</inline>
<inline name="PyGetRes">
- <script><code><![CDATA[print "retVec ";
-print retVec;
+ <script><code><![CDATA[print("retVec ");
+print(retVec);
res = "True";
for ret in retVec:
if not ret:
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>salome.salome_init()</code>
<code>import HELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "HELLO")</code>
- <code> print compo.hello(salome.myStudy, p1)</code>
- <code> print p1</code>
+ <code> print(compo.hello(salome.myStudy, p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<inport name="p1" type="string"/>
</sinline>
<code>salome.salome_init()</code>
<code>import HELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "HELLO")</code>
- <code> print compo.hello(salome.myStudy, p1)</code>
- <code> print p1</code>
+ <code> print(compo.hello(salome.myStudy, p1))</code>
+ <code> print(p1)</code>
</function>
<inport name="p1" type="string"/>
</sinline>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>import salome</code>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
- <code>print __container__from__YACS__</code>
+ <code>print(__container__from__YACS__)</code>
<code>machine,container=__container__from__YACS__.split('/')</code>
<code>param={}</code>
<code>param['hostname']=machine</code>
<code>param['container_name']=container</code>
<code>compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
<code>def f(p1):</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>salome.salome_init()</code>
<code>import HELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "HELLO")</code>
- <code> print compo.hello(salome.myStudy, p1)</code>
- <code> print p1</code>
+ <code> print(compo.hello(salome.myStudy, p1))</code>
+ <code> print(p1)</code>
</function>
<load container="A"/>
<inport name="p1" type="string"/>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
</function>
<inport name="p1" type="string"/>
</sinline>
<code>salome.salome_init()</code>
<code>import HELLO_ORB</code>
<code>def f(p1):</code>
- <code> print __container__from__YACS__</code>
+ <code> print(__container__from__YACS__)</code>
<code> machine,container=__container__from__YACS__.split('/')</code>
<code> param={}</code>
<code> param['hostname']=machine</code>
<code> param['container_name']=container</code>
<code> compo=salome.lcc.LoadComponent(param, "HELLO")</code>
- <code> print compo.hello(salome.myStudy, p1)</code>
- <code> print p1</code>
+ <code> print(compo.hello(salome.myStudy, p1))</code>
+ <code> print(p1)</code>
</function>
<inport name="p1" type="string"/>
</sinline>
<code>import salome</code>
<code>salome.salome_init()</code>
<code>import PYHELLO_ORB</code>
- <code>print __container__from__YACS__</code>
+ <code>print(__container__from__YACS__)</code>
<code>machine,container=__container__from__YACS__.split('/')</code>
<code>param={}</code>
<code>param['hostname']=machine</code>
<code>param['container_name']=container</code>
<code>compo=salome.lcc.LoadComponent(param, "PYHELLO")</code>
<code>def f(p1):</code>
- <code> print compo.makeBanner(p1)</code>
- <code> print p1</code>
+ <code> print(compo.makeBanner(p1))</code>
+ <code> print(p1)</code>
<code> return p1</code>
</function>
<load container="A"/>
</foreach>
<inline name="node1" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="strvec"/>
</inline>
<inline name="pyth5" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="strvec"/>
<outport name="p1" type="strvec"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="strvec"/>
<outport name="p1" type="strvec"/>
<inline name="pyth3" >
<script>
- <code>print s1</code>
+ <code>print(s1)</code>
</script>
<inport name="s1" type="eo/S2"/>
</inline>
<inline name="pyth9" >
<script>
- <code>print s1</code>
+ <code>print(s1)</code>
</script>
<inport name="s1" type="eo/S2"/>
</inline>
<inline name="pyth2" >
<script>
- <code>print s1</code>
+ <code>print(s1)</code>
</script>
<inport name="s1" type="eo/S2"/>
</inline>
<inline name="pyth0" >
<script>
- <code>print s1</code>
- <code>print t1</code>
+ <code>print(s1)</code>
+ <code>print(t1)</code>
</script>
<inport name="p1" type="double"/>
<inport name="s1" type="eo/S2"/>
<inline name="pyth6" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="dblevec"/>
<outport name="p1" type="dblevec"/>
<script>
<code>import GEOM</code>
<code>p1=p1._narrow(GEOM.GEOM_Object)</code>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="GEOM/GEOM_Object"/>
<outport name="p1" type="GEOM/GEOM_Object"/>
<switch name="b1" select="3" >
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<outport name="select" type="int"/>
</inline>
<inline name="n2">
- <script><code><![CDATA[print p1]]></code></script>
+ <script><code><![CDATA[print(p1)]]></code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<switch name="b1">
<default>
<inline name="n2">
- <script><code><![CDATA[print p1]]></code></script>
+ <script><code><![CDATA[print(p1)]]></code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</default>
<case id="1">
<inline name="n2">
- <script><code><![CDATA[print p1]]></code></script>
+ <script><code><![CDATA[print(p1)]]></code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</default>
<case id="1">
<inline name="n2">
- <script><code><![CDATA[print p1
+ <script><code><![CDATA[print(p1)
p1=p1+20
condition=p1 < 40. ]]></code></script>
<inport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<case id="3">
<bloc name="b">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<case id="3">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<case id="3">
<forloop name="b" nsteps="2">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<while name="b" >
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
<code>p1=p1+20</code>
<code><![CDATA[condition=p1 < 90.]]> </code>
</script>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
</inline>
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
</script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
<switch name="b1">
<case id="1">
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<case id="1">
<inline name="n2" >
<script>
- <code>print p1</code>
+ <code>print(p1)</code>
<code>p1=p1+20</code>
<code><![CDATA[condition=p1 < 40.]]> </code>
</script>
</case>
<default>
<inline name="n2" >
- <script><code>print p1</code></script>
+ <script><code>print(p1)</code></script>
<inport name="p1" type="double"/>
<outport name="p1" type="double"/>
</inline>
<inline name="node_0_0" >
<script><code>
c=a+b
-print c
+print(c)
</code></script>
<inport name="a" type="int"/>
<inport name="b" type="int"/>
<inline name="node_3_0" >
<script><code>
c=a+b/0
-print c
+print(c)
</code></script>
<inport name="a" type="int"/>
<inport name="b" type="int"/>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print "p1:",p1</code>
+ <code> print("p1:",p1)</code>
<code><![CDATA[ condition=p1 < 40.]]> </code>
<code> return p1,condition</code>
</function>
<code><![CDATA[def f(p1):]]> </code>
<code><![CDATA[ global a]]> </code>
<code><![CDATA[ p1= p1+10.]]> </code>
- <code><![CDATA[ print a]]> </code>
+ <code><![CDATA[ print(a)]]> </code>
<code><![CDATA[ a=a+p1]]> </code>
- <code><![CDATA[ print "a:",a]]> </code>
+ <code><![CDATA[ print("a:",a)]]> </code>
<code><![CDATA[ condition=p1 < 50.]]> </code>
<code><![CDATA[ return p1,condition]]> </code>
</function>
<code>def f(p1):</code>
<code> global a</code>
<code> p1= p1+10.</code>
- <code> print a</code>
+ <code> print(a)</code>
<code> a=a+p1</code>
- <code> print "p1:",p1</code>
+ <code> print("p1:",p1)</code>
<code><![CDATA[ condition=p1 < 40.]]> </code>
<code> return p1,condition</code>
</function>
${PROJECT_SOURCE_DIR}/src/yacsloader
${PROJECT_BINARY_DIR}/src/engine_swig
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PYTHON_INCLUDE_DIRS}
)
"""Optional method called on initialization.
The type of "input" is returned by "getTCForAlgoInit"
"""
- print "Algo initialize, input = ", input.getIntValue()
+ print("Algo initialize, input = ", input.getIntValue())
def start(self):
"""Start to fill the pool with samples to evaluate."""
- print "Algo start "
+ print("Algo start ")
self.iter=0
# pushInSample(id, value)
self.pool.pushInSample(self.iter, 1)
currentId=self.pool.getCurrentId()
valIn = self.pool.getCurrentInSample().getIntValue()
valOut = self.pool.getCurrentOutSample().getIntValue()
- print "Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut)
+ print("Algo takeDecision currentId=%s, valIn=%s, valOut=%s" % (currentId, valIn, valOut))
self.iter=self.iter+1
if self.iter < 3:
def finish(self):
"""Optional method called when the algorithm has finished, successfully
or not, to perform any necessary clean up."""
- print "Algo finish"
+ print("Algo finish")
self.pool.destroyAll()
def getAlgoResult(self):
def test1_edit(self):
p = self.r.createProc("pr")
- print p.typeMap
+ print(p.typeMap)
t=p.getTypeCode("double")
- print t.kind()
+ print(t.kind())
t=p.typeMap["double"]
td=p.createType("double","double")
ti=p.createType("int","int")
tc1=p.createInterfaceTc("","Obj",[])
- print tc1.name(),tc1.id()
+ print(tc1.name(),tc1.id())
tc2=p.createInterfaceTc("","Obj2",[tc1])
- print tc2.name(),tc2.id()
+ print(tc2.name(),tc2.id())
tc3=p.createSequenceTc("","seqdbl",td)
- print tc3.name(),tc3.id(),tc3.contentType()
+ print(tc3.name(),tc3.id(),tc3.contentType())
tc4=p.createSequenceTc("","seqObj2",tc2)
tc5=p.createSequenceTc("","seqint",ti)
- print tc4.name(),tc4.id()
- print tc4.isA(tc1),0
- print tc2.isA(tc1),1
- print tc1.isA(tc2),0
- print td.isA(ti),0
- print td.isAdaptable(ti),1
- print ti.isAdaptable(td),0
- print tc5.isAdaptable(tc3),0
- print tc3.isAdaptable(tc5),1
+ print(tc4.name(),tc4.id())
+ print(tc4.isA(tc1),0)
+ print(tc2.isA(tc1),1)
+ print(tc1.isA(tc2),0)
+ print(td.isA(ti),0)
+ print(td.isAdaptable(ti),1)
+ print(ti.isAdaptable(td),0)
+ print(tc5.isAdaptable(tc3),0)
+ print(tc3.isAdaptable(tc5),1)
n=self.r.createScriptNode("","node1")
- n.setScript("print 'coucou1'")
+ n.setScript("print('coucou1')")
n.edAddInputPort("p1",ti)
n.edAddOutputPort("p1",ti)
p.edAddChild(n)
retex=None
try:
inport.edInitXML("<value><intt>5</int></value>")
- except ValueError, ex:
- print "Value Error: ", ex
+ except ValueError as ex:
+ print("Value Error: ", ex)
retex=ex
- except pilot.Exception,ex:
- print "YACS exception:",ex.what()
+ except pilot.Exception as ex:
+ print("YACS exception:",ex.what())
retex=ex.what()
- self.assert_(retex is not None, "exception not raised, or wrong type")
+ self.assertTrue(retex is not None, "exception not raised, or wrong type")
inport.edInitXML("<value><int>5</int></value>")
# --- create script node node2
n2=self.r.createScriptNode("","node2")
- n2.setScript("print 'coucou2'")
+ n2.setScript("print('coucou2')")
n2.edAddInputPort("p1",ti)
p.edAddChild(n2)
# --- end of node
n=self.r.createFuncNode("","node3")
n.setScript("""
def f():
- print 'coucou3'
+ print('coucou3')
""")
n.setFname("f")
p.edAddChild(n)
p.edAddChild(b)
n=self.r.createScriptNode("","b1.node2")
- n.setScript("print 'coucou2'")
+ n.setScript("print('coucou2')")
b.edAddChild(n)
# --- end bloc
ip.edInitInt(3)
n=self.r.createScriptNode("","l1.node2")
- n.setScript("print 'coucou2'")
+ n.setScript("print('coucou2')")
lo.edSetNode(n)
# --- end loop
n=self.r.createFuncNode("","w1.node3")
n.setScript("""
def f():
- print 'coucou3'
+ print('coucou3')
return 0
""")
n.setFname("f")
n=self.r.createFuncNode("","sw1.node3")
n.setScript("""
def f():
- print 'case1'
+ print('case1')
return 0
""")
n.setFname("f")
n=self.r.createFuncNode("","sw1.node4")
n.setScript("""
def f():
- print 'default'
+ print('default')
return 0
""")
n.setFname("f")
try:
self.e.RunW(p,0)
- except pilot.Exception,ex:
- print ex.what()
+ except pilot.Exception as ex:
+ print(ex.what())
self.fail(ex)
#self.e.displayDot(p)
def test1_StepByStep(self):
# --- execution step by step
- print "================= Start of STEPBYSTEP ==================="
+ print("================= Start of STEPBYSTEP ===================")
self.e.setExecMode(1) # YACS::STEPBYSTEP
run1 = threading.Thread(None, self.e.RunPy, "stepbystep", (self.p,0))
self.e.waitPause()
#e.displayDot(p)
bp = self.e.getTasksToLoad()
- print "nexts possible steps = ", bp
+ print("nexts possible steps = ", bp)
if len(bp) > 0:
tte= bp[-1:] # only one node at each step, the last one in the list
r = self.e.setStepsToExecute(tte)
else:
tocont = False
pass
- print "toContinue = ", tocont
+ print("toContinue = ", tocont)
pass
self.e.resumeCurrentBreakPoint()
self.assertEqual(106, self.p.getChildByName('c0.c1.n1').getEffectiveState())
self.assertEqual(999, self.p.getChildByName('c0.n2').getEffectiveState())
self.assertEqual(888, self.p.getChildByName('node62').getEffectiveState())
- print "================= End of STEPBYSTEP ====================="
+ print("================= End of STEPBYSTEP =====================")
pass
def test2_StopToBreakpoint(self):
# --- start execution, set a breakpoint before node48, then continue
time.sleep(1)
- print "================= Start of BREAKPOINT ==================="
+ print("================= Start of BREAKPOINT ===================")
brp=['node48']
self.e.setListOfBreakPoints(brp)
self.e.setExecMode(2) # YACS::STOPBEFORENODES
time.sleep(0.1)
self.e.waitPause()
#self.e.displayDot(p)
- print "================= reach BREAKPOINT ======================"
+ print("================= reach BREAKPOINT ======================")
# --- resume from breakpoint
- print "=========== BREAKPOINT, start RESUME ===================="
+ print("=========== BREAKPOINT, start RESUME ====================")
time.sleep(1)
self.e.setExecMode(0) # YACS::CONTINUE
self.e.resumeCurrentBreakPoint()
self.assertEqual(106, self.p.getChildByName('c0.c1.n1').getEffectiveState())
self.assertEqual(999, self.p.getChildByName('c0.n2').getEffectiveState())
self.assertEqual(888, self.p.getChildByName('node62').getEffectiveState())
- print "================= End of RESUME ========================="
+ print("================= End of RESUME =========================")
pass
def test3_RunWithoutBreakpoints(self):
# --- start execution, run without breakpoints
time.sleep(1)
- print "================= Start of CONTINUE ====================="
+ print("================= Start of CONTINUE =====================")
self.e.setExecMode(0) # YACS::CONTINUE
run3 = threading.Thread(None, self.e.RunPy, "continue", (self.p,0))
run3.start()
self.assertEqual(106, self.p.getChildByName('c0.c1.n1').getEffectiveState())
self.assertEqual(999, self.p.getChildByName('c0.n2').getEffectiveState())
self.assertEqual(888, self.p.getChildByName('node62').getEffectiveState())
- print "================= End of CONTINUE ======================="
+ print("================= End of CONTINUE =======================")
pass
def test4_StopOnError(self):
# --- stop execution on first error and save state
time.sleep(1)
- print "================= Start of STOPONERROR =================="
+ print("================= Start of STOPONERROR ==================")
self.e.setStopOnError()
run4 = threading.Thread(None, self.e.RunPy, "continue", (self.p,0))
run4.start()
#self.e.displayDot(self.p)
s13 = self.p.getChildByName('node13').getEffectiveState()
s43 = self.p.getChildByName('node43').getEffectiveState()
- self.assert_((s13==999) or (s43==999))
- print "================= End of STOPONERROR ====================="
+ self.assertTrue((s13==999) or (s43==999))
+ print("================= End of STOPONERROR =====================")
pass
def test5_PartialExec(self):
# --- stop execution after breakpoint
time.sleep(1)
- print "================= Start of PARTIALEXEC ==================="
+ print("================= Start of PARTIALEXEC ===================")
brp=['node35']
self.e.setListOfBreakPoints(brp)
self.e.setExecMode(2) # YACS::STOPBEFORENODES
#self.e.displayDot(self.p)
self.assertEqual(106, self.p.getChildByName('node34').getEffectiveState())
self.assertEqual(101, self.p.getChildByName('node35').getEffectiveState())
- print "================= reach BREAKPOINT PARTIAL EXEC =========="
+ print("================= reach BREAKPOINT PARTIAL EXEC ==========")
pass
pass
retex=None
try:
p = self.l.load("nonexisting")
- except IOError, ex:
- print "IO Error: ", ex
+ except IOError as ex:
+ print("IO Error: ", ex)
retex=ex
- #except pilot.invalid_argument,ex:
- # print "invalid_argument:",ex.what()
+ # except pilot.invalid_argument as ex:
+ # print("invalid_argument:",str(ex))
# retex=ex.what()
- self.assert_(retex is not None, "exception not raised, or wrong type")
+ self.assertTrue(retex is not None, "exception not raised, or wrong type")
pass
def test2_parseError(self):
retex=None
try:
p = self.l.load("samples/bid.xml")
- except ValueError,ex:
- print "Caught ValueError Exception:",ex
+ except ValueError as ex:
+ print("Caught ValueError Exception:",ex)
retex = ex
expected="LogRecord: parser:ERROR:from node node5 does not exist in control link: node5->b2 context: b1. (samples/bid.xml:53)\n"
- self.assert_(p.getLogger("parser").getStr() == expected, "error not found: "+p.getLogger("parser").getStr())
+ self.assertTrue(p.getLogger("parser").getStr() == expected, "error not found: "+p.getLogger("parser").getStr())
pass
def test3_normal(self):
# --- File exists and no parsing problem
try:
p = self.l.load("samples/aschema.xml")
- print p.getLogger("parser").getStr()
- print p
- print p.getName()
- for k in p.typeMap: print k
- for k in p.nodeMap: print k
- for k in p.inlineMap: print k
- for k in p.serviceMap: print k
- print self.e.getTasksToLoad()
+ print(p.getLogger("parser").getStr())
+ print(p)
+ print(p.getName())
+ for k in p.typeMap: print(k)
+ for k in p.nodeMap: print(k)
+ for k in p.inlineMap: print(k)
+ for k in p.serviceMap: print(k)
+ print(self.e.getTasksToLoad())
self.e.RunW(p,0)
self.assertEqual(106, p.getChildByName('node48').getEffectiveState())
- except pilot.Exception,ex:
- print "YACS exception:",ex
+ except pilot.Exception as ex:
+ print("YACS exception:",ex)
self.fail(ex)
pass
pass
suite = unittest.makeSuite(TestLoader)
result=unittest.TextTestRunner(f, descriptions=1, verbosity=1).run(suite)
f.close()
- sys.exit(not result.wasSuccessful())
\ No newline at end of file
+ sys.exit(not result.wasSuccessful())
"""test delete following creation from class"""
co=self.r.createContainer()
self.assertEqual(co.getRefCnt(), 1)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
def test1(self):
"""test delete following creation from createContainer and delitem from containerMap"""
co=self.p.createContainer("c2")
del self.p.containerMap["c2"]
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 1)
del co
co=self.p.createContainer("c2")
self.p.containerMap["c2"]=co
del self.p.containerMap["c2"]
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 1)
del co
del self.p.containerMap["c9"]
self.assertEqual(co.getName(), "c9")
self.assertEqual(co.getRefCnt(), 1)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
def test4(self):
del self.p.containerMap["c10"]
self.assertEqual(co.getName(), "c10")
self.assertEqual(co.getRefCnt(), 1)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
def test5(self):
del self.p
self.assertEqual(co.getName(), "c10")
self.assertEqual(co.getRefCnt(), 1)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
def test6(self):
"""test ownership of container on getitem from containerMap"""
co=self.p.createContainer("c8")
self.assertEqual(co.getRefCnt(), 2)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
self.assertEqual(self.p.containerMap["c8"].getRefCnt(), 2) # +1 for getitem
co=self.p.containerMap["c8"]
self.assertEqual(co.getRefCnt(), 2)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
del co
self.assertEqual(self.p.containerMap["c8"].getRefCnt(), 2) # +1 for getitem
del self.p.containerMap["c8"]
def test9(self):
"""test method values"""
self.p.createContainer("c8")
- for co in self.p.containerMap.values():
- self.assert_(co.thisown)
+ for co in list(self.p.containerMap.values()):
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 2)
def test10(self):
"""test method items"""
self.p.createContainer("c8")
- for k,co in self.p.containerMap.items():
- self.assert_(co.thisown)
+ for k,co in list(self.p.containerMap.items()):
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 2)
def test11(self):
"""test method clear"""
co=self.p.createContainer("c8")
self.p.containerMap.clear()
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 1)
def test12(self):
co=self.p.createContainer("c8")
d={"c1":co}
self.p.containerMap.update(d)
- self.assert_(co.thisown)
+ self.assertTrue(co.thisown)
self.assertEqual(co.getRefCnt(), 3)
class TestTypeCodeRef(unittest.TestCase):
"""test delete following creation from createSequenceTc"""
tc=pilot.TypeCode(pilot.Double)
self.assertEqual(tc.getRefCnt(), 1)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
def test1(self):
"""test delete following creation from createInterfaceTc and delitem from typeMap"""
tc=self.p.createInterfaceTc("","obj",[])
del self.p.typeMap["obj"]
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 1)
def test2(self):
tc=self.p.createInterfaceTc("","obj",[])
self.p.typeMap["obj"]=tc
del self.p.typeMap["obj"]
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 1)
def test3(self):
self.assertEqual(tc.getRefCnt(), 2)
del self.p.typeMap["obj"]
self.assertEqual(tc.getRefCnt(), 1)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
def test4(self):
"""test delete from typeMap following creation from createInterfaceTc"""
tc=self.p.createInterfaceTc("","obj",[])
del self.p.typeMap["obj"]
self.assertEqual(tc.getRefCnt(), 1)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
def test5(self):
"""test existence TypeCode following delete proc"""
tc=self.p.createInterfaceTc("","obj",[])
del self.p
self.assertEqual(tc.getRefCnt(), 1)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
def test6(self):
"""test ownership of TypeCode on getitem from typeMap"""
tc=self.p.createInterfaceTc("","obj",[])
self.assertEqual(tc.getRefCnt(), 2)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
del tc
self.assertEqual(self.p.typeMap["obj"].getRefCnt(), 2) # +1 for getitem
tc=self.p.typeMap["obj"]
self.assertEqual(tc.getRefCnt(), 2)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
del tc
self.assertEqual(self.p.typeMap["obj"].getRefCnt(), 2) # +1 for getitem
del self.p.typeMap["obj"]
def test9(self):
"""test method values"""
self.p.createInterfaceTc("","obj",[])
- for tc in self.p.typeMap.values():
+ for tc in list(self.p.typeMap.values()):
if tc.name()!="obj":continue
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 2)
def test10(self):
"""test method items"""
self.p.createInterfaceTc("","obj",[])
- for k,tc in self.p.typeMap.items():
+ for k,tc in list(self.p.typeMap.items()):
if tc.name()!="obj":continue
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 2)
def test11(self):
"""test method clear"""
tc=self.p.createInterfaceTc("","obj",[])
self.p.typeMap.clear()
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 1)
def test12(self):
tc=self.p.createInterfaceTc("","obj",[])
d={"c1":tc}
self.p.typeMap.update(d)
- self.assert_(tc.thisown)
+ self.assertTrue(tc.thisown)
self.assertEqual(tc.getRefCnt(), 3)
if __name__ == '__main__':
# --- stop execution after breakpoint
time.sleep(1)
- print "================= Start of PARTIALEXEC ==================="
+ print("================= Start of PARTIALEXEC ===================")
brp=['b1.b2.node1']
self.e.setListOfBreakPoints(brp)
self.e.setExecMode(2) # YACS::STOPBEFORENODES
#self.e.displayDot(self.p)
self.assertEqual(101, self.p.getChildByName('b1.b2.node1').getEffectiveState())
self.assertEqual(106, self.p.getChildByName('b1.node1').getEffectiveState())
- print "================= reach BREAKPOINT PARTIAL EXEC =========="
+ print("================= reach BREAKPOINT PARTIAL EXEC ==========")
pass
def test2_ExecFromLoadState(self):
# --- reload state from previous partial execution then exec
time.sleep(1)
- print "================= Start of EXECLOADEDSTATE ==============="
+ print("================= Start of EXECLOADEDSTATE ===============")
sp = loader.stateParser()
sl = loader.stateLoader(sp,self.p)
sl.parse('dumpPartialBloc2.xml')
self.assertEqual(106, self.p.getChildByName('b1.b2.node1').getEffectiveState())
self.assertEqual(106, self.p.getChildByName('b1.b2.node2').getEffectiveState())
self.assertEqual(106, self.p.getChildByName('b1.b2.loop1.node1').getEffectiveState())
- print "================= End of EXECLOADEDSTATE ================="
+ print("================= End of EXECLOADEDSTATE =================")
pass
s.save(saveSchema2)
e.RunW(p,0)
e.saveState(dumpSchema2)
- except ValueError, ex:
- print "Value Error: ", ex
+ except ValueError as ex:
+ print("Value Error: ", ex)
pb = "problem on " + fileOrig + " : ValueError"
self.fail(pb)
- except pilot.Exception,ex:
- print ex.what()
+ except pilot.Exception as ex:
+ print(ex.what())
pb = "problem on " + fileOrig + " : " + ex.what()
self.fail(pb)
except:
ref=datetime.datetime.now()
t=0. ; pas=1./float(nb)
- for i in xrange(nb):
- for j in xrange(nb):
+ for i in range(nb):
+ for j in range(nb):
x=j*pas
t+=1.+cos(1.*(x*3.14159))
pass
pass
- print "coucou from script0-%i -> %s"%(dbg,str(datetime.datetime.now()-ref))
+ print("coucou from script0-%i -> %s"%(dbg,str(datetime.datetime.now()-ref)))
return t
"""
script1="""
import datetime
ref=datetime.datetime.now()
o2=0. ; pas=1./float(i1)
-for i in xrange(i1):
- for j in xrange(i1):
+for i in range(i1):
+ for j in range(i1):
x=j*pas
o2+=1.+cos(1.*(x*3.14159))
pass
-print "coucou from script1-%i -> %s"%(dbg,str(datetime.datetime.now()-ref))
+print("coucou from script1-%i -> %s"%(dbg,str(datetime.datetime.now()-ref)))
"""
- for i in xrange(nbOfNodes):
+ for i in range(nbOfNodes):
node0=self.r.createFuncNode("DistPython","node%i"%(i))
p.edAddChild(node0)
node0.setFname("ff")
st=datetime.datetime.now()
# 1st exec
ex.RunW(p,0)
- print "Time spend of test0 to run 1st %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test0 to run 1st %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
# 2nd exec using the same already launched remote python interpreters
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test0 to run 2nd %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test0 to run 2nd %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
# 3rd exec using the same already launched remote python interpreters
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test0 to run 3rd %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test0 to run 3rd %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
pass
ref=datetime.datetime.now()
t=0. ; pas=1./float(nb)
- for i in xrange(nb):
- for j in xrange(nb):
+ for i in range(nb):
+ for j in range(nb):
x=j*pas
t+=1.+cos(1.*(x*3.14159))
pass
pass
- print "coucou from script0-%i -> %s"%(dbg,str(datetime.datetime.now()-ref))
+ print("coucou from script0-%i -> %s"%(dbg,str(datetime.datetime.now()-ref)))
return t
"""
# here in script1 aa is refered ! aa will exist thanks to HPCont Init Script
import datetime
ref=datetime.datetime.now()
o2=0. ; pas=1./float(i1)
-for i in xrange(i1):
- for j in xrange(i1):
+for i in range(i1):
+ for j in range(i1):
x=j*pas
o2+=1.+cos(1.*(x*3.14159))
pass
-print "coucou %lf from script1-%i -> %s"%(aa,dbg,str(datetime.datetime.now()-ref))
+print("coucou %lf from script1-%i -> %s"%(aa,dbg,str(datetime.datetime.now()-ref)))
aa+=1.
"""
#
- for i in xrange(nbOfNodes):
+ for i in range(nbOfNodes):
nodeMiddle=self.r.createFuncNode("Salome","node%i_1"%(i)) # PyFuncNode remote
p.edAddChild(nodeMiddle)
nodeMiddle.setFname("ff")
self.assertEqual(p.getState(),pilot.READY)
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test1 to 1st run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test1 to 1st run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
# 2nd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test1 to 2nd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test1 to 2nd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
# 3rd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test1 to 3rd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test1 to 3rd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
pass
""" Test on HP Containers in foreach context."""
script0="""def ff():
global aa
- print "%%lf - %%s"%%(aa,str(my_container))
+ print("%%lf - %%s"%%(aa,str(my_container)))
return 16*[%i],0
"""
script1="""from math import cos
import datetime
ref=datetime.datetime.now()
o2=0. ; pas=1./float(i1)
-for i in xrange(i1):
- for j in xrange(i1):
+for i in range(i1):
+ for j in range(i1):
x=j*pas
o2+=1.+cos(1.*(x*3.14159))
pass
-print "coucou %lf from script -> %s"%(aa,str(datetime.datetime.now()-ref))
+print("coucou %lf from script -> %s"%(aa,str(datetime.datetime.now()-ref)))
aa+=1.
o3=0
"""
self.assertEqual(p.getState(),pilot.READY)
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test2 to 1st run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test2 to 1st run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
# 2nd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test2 to 2nd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test2 to 2nd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
# 3rd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test2 to 3rd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test2 to 3rd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
pass
""" Test that focuses on parallel load of containers."""
script0="""def ff():
global aa
- print "%%lf - %%s"%%(aa,str(my_container))
+ print("%%lf - %%s"%%(aa,str(my_container)))
return 100*[%i],0
"""
script1="""from math import cos
import datetime
ref=datetime.datetime.now()
o2=0. ; pas=1./float(i1)
-for i in xrange(i1):
- for j in xrange(i1):
+for i in range(i1):
+ for j in range(i1):
x=j*pas
o2+=1.+cos(1.*(x*3.14159))
pass
-print "coucou %lf from script -> %s"%(aa,str(datetime.datetime.now()-ref))
+print("coucou %lf from script -> %s"%(aa,str(datetime.datetime.now()-ref)))
aa+=1.
o3=0
"""
self.assertEqual(p.getState(),pilot.READY)
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test3 to 1st run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test3 to 1st run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
# 2nd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test3 to 2nd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test3 to 2nd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
# 3rd exec
st=datetime.datetime.now()
ex.RunW(p,0)
- print "Time spend of test3 to 3rd run %s"%(str(datetime.datetime.now()-st))
+ print("Time spend of test3 to 3rd run %s"%(str(datetime.datetime.now()-st)))
self.assertEqual(p.getState(),pilot.DONE)
self.assertAlmostEqual(refExpected,o9.getPyObj(),5)
pass
script1="""nb=7
ii=0
o1=nb*[None]
-for i in xrange(nb):
+for i in range(nb):
tmp=(i+10)*[None]
- for j in xrange(i+10):
+ for j in range(i+10):
tmp[j]=ii
ii+=1
pass
script1="""nb=7
ii=0
o1=nb*[None]
-for i in xrange(nb):
+for i in range(nb):
tmp=(i+10)*[None]
- for j in xrange(i+10):
+ for j in range(i+10):
tmp[j]=ii
ii+=1
pass
self.assertEqual(n1.getState(),pilot.DONE)
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
- self.assertEqual(a,range(6))
- self.assertEqual([elt.getPyObj() for elt in b],[[6L, 12L, 16L, 18L, -4L, 10L]])
+ self.assertEqual(a,list(range(6)))
+ self.assertEqual([elt.getPyObj() for elt in b],[[6, 12, 16, 18, -4, 10]])
self.assertEqual(c,['n10_o2_interceptor'])
pass
self.assertEqual(n1.getState(),pilot.FAILED)
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
- self.assertEqual(a,range(3))
- self.assertEqual([elt.getPyObj() for elt in b],[[6L,12L,16L]])
+ self.assertEqual(a,list(range(3)))
+ self.assertEqual([elt.getPyObj() for elt in b],[[6,12,16]])
self.assertEqual(c,['n10_o2_interceptor'])
pass
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
self.assertEqual(a,[0,1,2,4,5])
- self.assertEqual([elt.getPyObj() for elt in b],[[6L,12L,16L,-4L,10L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[6,12,16,-4,10]])
self.assertEqual(c,['n10_o2_interceptor'])
p.getChildByName("n1").getChildByName("n10").setScript("""
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
self.assertEqual(a,[1,2,3,4,5])
- self.assertEqual([elt.getPyObj() for elt in b],[[12L,16L,18L,-4L,10L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[12,16,18,-4,10]])
self.assertEqual(c,['n10_o2_interceptor'])
pass
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
self.assertEqual(a,[0,1,2,4,5])
- self.assertEqual([elt.getPyObj() for elt in b],[[6L,12L,16L,-4L,10L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[6,12,16,-4,10]])
self.assertEqual(c,['n10_o2_interceptor'])
p.getChildByName("n1").getChildByName("n10").setScript("""
#
self.assertEqual(n1.getState(),pilot.DONE)
self.assertEqual(p.getState(),pilot.DONE)
- self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[6L,12L,16L,63L,-4L,10L])
+ self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[6,12,16,63,-4,10])
pass
def test10(self):
n1.edGetSeqOfSamplesPort().getPyObj()
a,b,c=n1.getPassedResults(ex)
self.assertEqual(a,[1,3,5,7,9,11])
- self.assertEqual([elt.getPyObj() for elt in b],[[12L,36L,60L,84L,108L,132L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[12,36,60,84,108,132]])
self.assertEqual(c,['n10_o2_interceptor'])
p.getChildByName("n1").getChildByName("n10").setScript("""
#
self.assertEqual(n1.getState(),pilot.DONE)
self.assertEqual(p.getState(),pilot.DONE)
- self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0L,12L,30L,36L,60L,60L,90L,84L,120L,108L,150L,132L])
+ self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0,12,30,36,60,60,90,84,120,108,150,132])
pass
pass
a,b,c=n1.getPassedResults(ex)
self.assertEqual(a,[0,2,4,6,8,10])
- self.assertEqual([elt.getPyObj() for elt in b],[[0L,4L,8L,12L,16L,20L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[0,4,8,12,16,20]])
p.getChildByName("n0").setScript("o0=[ 3*elt for elt in range(12) ]")
p.getChildByName("n1").getChildByName("n10").setScript("""
#
self.assertEqual(n1.getState(),pilot.DONE)
self.assertEqual(p.getState(),pilot.DONE)
- self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0L,5L,4L,15L,8L,25L,12L,35L,16L,45L,20L,55L])
+ self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0,5,4,15,8,25,12,35,16,45,20,55])
pass
def test12(self):
#
node0=self.r.createForEachLoop("ForEachLoop_int0",ti)
p.edAddChild(node0)
- node0.edGetSeqOfSamplesPort().edInitPy(range(4))
+ node0.edGetSeqOfSamplesPort().edInitPy(list(range(4)))
node0.edGetNbOfBranchesPort().edInitInt(2)
#
node00=self.r.createBloc("Bloc0")
node0.edAddChild(node00)
node000_0=self.r.createForEachLoop("ForEachLoop_int1",ti)
node00.edAddChild(node000_0)
- node000_0.edGetSeqOfSamplesPort().edInitPy(range(4))
+ node000_0.edGetSeqOfSamplesPort().edInitPy(list(range(4)))
node000_0.edGetNbOfBranchesPort().edInitInt(3)
#
node0000=self.r.createBloc("Bloc1")
node00.edAddChild(node000_1)
i7=node000_1.edAddInputPort("i7",ti2)
i5=node000_1.edAddInputPort("i5",ti2)
- node000_1.setScript("for i in i7:\n print i\nprint \"separation\"\nfor i in i5:\n print i")
+ node000_1.setScript("for i in i7:\n print(i)\nprint(\"separation\")\nfor i in i5:\n print(i)")
node000_1.setContainer(cont)
node000_1.setExecutionMode("remote")
p.edAddLink(o5,i7)
#
n00.edAddLink(n000.edGetSamplePort(),i0)
#
- n000.edGetSeqOfSamplesPort().edInitPy(range(10))
+ n000.edGetSeqOfSamplesPort().edInitPy(list(range(10)))
n000.edGetNbOfBranchesPort().edInitInt(2)
#
n01=r.createScriptNode("Salome","test23/check") ; n0bis.edAddChild(n01)
#
nb=4
outs=[]
- for i in xrange(nb):
+ for i in range(nb):
node=self.r.createScriptNode("Salome","node%d"%i)
node.setExecutionMode("remote")
node.setContainer(cont)
res=node.edAddOutputPort("res",ti)
p.edAddChild(node)
l=[]
- for i in xrange(nb):
+ for i in range(nb):
elt="i%d"%i
inp=node.edAddInputPort(elt,ti) ; l.append(elt)
p.edAddChild(node)
node.setScript("res="+"+".join(l))
p.edAddCFLink(b,node)
#
- for i in xrange(10):
+ for i in range(10):
p.init()
ex = pilot.ExecutorSwig()
self.assertEqual(p.getState(),pilot.READY)
n00=self.r.createScriptNode("Salome","n00") ; n0.edAddChild(n00)
o0=n00.edAddOutputPort("o0",tp2)
- n00.setScript("o0=[[i+1] for i in xrange(8)]")
+ n00.setScript("o0=[[i+1] for i in range(8)]")
n01=self.r.createScriptNode("Salome","n01") ; n0.edAddChild(n01)
i1=n01.edAddInputPort("i1",tp)
n01.setScript("assert(i1==[[1], [2], [3], [4], [5], [6], [7], [8]])")
n00=self.r.createScriptNode("Salome","n00") ; n0.edAddChild(n00)
o0=n00.edAddOutputPort("o0",tp2)
- n00.setScript("o0=[[i+1] for i in xrange(8)]")
+ n00.setScript("o0=[[i+1] for i in range(8)]")
n01=self.r.createScriptNode("Salome","n01") ; n0.edAddChild(n01)
i1=n01.edAddInputPort("i1",tp)
n01.setScript("assert(i1==[[1], [2], [3], [4], [5], [6], [7], [8]])")
self.assertEqual(p.getState(),pilot.DONE)
self.assertEqual(n1.getState(),pilot.DONE)
self.assertEqual(a,[0,1])
- self.assertEqual([elt.getPyObj() for elt in b],[[0L,2L]])
+ self.assertEqual([elt.getPyObj() for elt in b],[[0,2]])
#
p.getChildByName("n0").setScript("o0=[ 3*elt for elt in range(6) ]")
p.getChildByName("n1").getChildByName("n10").setScript("""
#
self.assertEqual(n1.getState(),pilot.DONE)
self.assertEqual(p.getState(),pilot.DONE)
- self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0L,2L,10L,15L,20L,25L])
+ self.assertEqual(p.getChildByName("n2").getOutputPort("o4").getPyObj(),[0,2,10,15,20,25])
pass
pass
time.sleep(0.5)
state = procEx.getExecutorState()
isRunning = (state < 304)
- print "executorState: ", state
+ print("executorState: ", state)
pass
procEx.saveState("res.xml")
i+=1
pass
-print procEx.getOutPortValue(dico["poly_7"],"Pn")
-print procEx.getInPortValue(dico["poly_7"],"x")
-print procEx.getInPortValue(dico["poly_7"],"notAPort")
-print procEx.getInPortValue(dico["Legendre.loopIter"],"nsteps")
+print(procEx.getOutPortValue(dico["poly_7"],"Pn"))
+print(procEx.getInPortValue(dico["poly_7"],"x"))
+print(procEx.getInPortValue(dico["poly_7"],"notAPort"))
+print(procEx.getInPortValue(dico["Legendre.loopIter"],"nsteps"))
# -----------------------------------------------------------------------------
# --- schema with errors (echoSrv must be launched)
time.sleep(0.5)
state = procEx.getExecutorState()
isRunning = (state < 304)
- print "executorState: ", state
+ print("executorState: ", state)
pass
procEx.saveState("res2.xml")
i+=1
pass
-print procEx.getErrorDetails(dico["c1"])
-print procEx.getErrorDetails(dico["node13"])
+print(procEx.getErrorDetails(dico["c1"]))
+print(procEx.getErrorDetails(dico["node13"]))
# -----------------------------------------------------------------------------
# --- schema with errors
time.sleep(0.5)
state = procEx.getExecutorState()
isRunning = (state < 304)
- print "executorState: ", state
+ print("executorState: ", state)
pass
#procEx.resumeCurrentBreakPoint()
time.sleep(0.5)
state = procEx.getExecutorState()
isRunning = (state < 304)
- print "executorState: ", state
+ print("executorState: ", state)
pass
procEx.saveState("partialExec.xml")
time.sleep(0.5)
state = procEx.getExecutorState()
isRunning = (state < 304)
- print "executorState: ", state
+ print("executorState: ", state)
pass
procEx.saveState("finishExec.xml")
return self.p.getIds()
def runProc(self,debug, isPyThread, fromscratch):
- print "**************************Begin schema execution %s**************************" % self.xmlFile
+ print("**************************Begin schema execution %s**************************" % self.xmlFile)
self.e.RunPy(self.p,debug, isPyThread, fromscratch)
- print "**************************End schema execution %s****************************" % self.xmlFile
+ print("**************************End schema execution %s****************************" % self.xmlFile)
def Run(self):
if self.run1 is not None:
sp = loader.stateParser()
sl = loader.stateLoader(sp,self.p)
sl.parse(xmlFile)
- except IOError, ex:
- print "IO Error: ", ex
+ except IOError as ex:
+ print("IO Error: ", ex)
return
- except ValueError,ex:
- print "Caught ValueError Exception:",ex
+ except ValueError as ex:
+ print("Caught ValueError Exception:",ex)
return
- except pilot.Exception,ex:
- print ex.what()
+ except pilot.Exception as ex:
+ print(ex.what())
return
except:
- print "Unknown exception!"
+ print("Unknown exception!")
return
if self.run1 is None:
"""
def __init__ ( self, orb, poa, contID, containerName, instanceName,
interfaceName ):
- print "YACS.__init__: ", containerName, ';', instanceName
+ print("YACS.__init__: ", containerName, ';', instanceName)
SALOME_ComponentPy.SALOME_ComponentPy_i.__init__(self, orb, poa, contID,
containerName, instanceName,
interfaceName, False)
procExec_i = proc_i(xmlFile)
logger=procExec_i.p.getLogger("parser")
if not logger.isEmpty():
- print "The imported file has errors :"
- print logger.getStr()
+ print("The imported file has errors :")
+ print(logger.getStr())
sys.stdout.flush()
return None
- except IOError, ex:
- print >> sys.stderr ,"IO Error: ", ex
+ except IOError as ex:
+ print("IO Error: ", ex, file=sys.stderr)
return None
- except ValueError,ex:
- print >> sys.stderr ,"Caught ValueError Exception:",ex
+ except ValueError as ex:
+ print("Caught ValueError Exception:",ex, file=sys.stderr)
return None
- except pilot.Exception,ex:
- print >> sys.stderr ,ex.what()
+ except pilot.Exception as ex:
+ print(ex.what(), file=sys.stderr)
return None
except:
traceback.print_exc()
YACSEvalParamsForCluster& ps(res->getAddParamsForCluster());
_clusterAdvInfo->applyToParams(ps);
}
- emit readyForRunSignal(true);
+ Q_EMIT readyForRunSignal(true);
}
QString YDFXGUIHostParametrizer::getNameOfHost()
ok->setDisabled(!isInterac && !_clusterAdvInfo->isOK());
if(_wasInteractive!=isInterac)
{
- emit interactivityChanged(isInterac);
+ Q_EMIT interactivityChanged(isInterac);
_wasInteractive=isInterac;
}
}
}
bool newOK(isOK());
_wasOK=newOK;
- emit statusOfEntryChanged(newOK);
+ Q_EMIT statusOfEntryChanged(newOK);
}
void YDFXGUIBatchInfo::learnSettings(QSettings& settings) const
void YDFXGUIBatchInfo::somethingChanged()
{
- emit statusOfEntryChanged(isOK());
+ Q_EMIT statusOfEntryChanged(isOK());
}
QString YDFXGUIBatchInfo::NormalizeDuration(const QString& txt)
#include <QThread>
#include <QMutex>
-#include "Python.h"
-
class YACSEvalSession;
class YACSEvalYFXWrap;
class YDFXGUIAllPorts;
{
if(wasKO)
{
- emit statusChanged();
+ Q_EMIT statusChanged();
disconnect(this,SIGNAL(changeLook()),this,SLOT(applyModificationOfLook()));
}
}
bool oldOK(isOK());
bool oldStatus(_inp->isRandomVar());
_inp->declareRandomnessStatus(!oldStatus);
- emit statusChanged(); // always emit because this even if newOK and oldOK are the same the upon status can changed !
+ Q_EMIT statusChanged(); // always Q_EMIT because this even if newOK and oldOK are the same the upon status can changed !
updateGeometry();
update();
return _inp->isRandomVar();
void InputLabel::pressOccured()
{
- emit randomnessStatusChanged();
+ Q_EMIT randomnessStatusChanged();
}
std::vector<ColoredString> InputLabel::textForEmulatedPushButton() const
{
bool oldStatus(_outp->isQOfInterest());
_outp->setQOfInterestStatus(!oldStatus);
- emit clicked();
+ Q_EMIT clicked();
}
std::vector<ColoredString> OutputLabel::textForEmulatedPushButton() const
update();
setWasOKStatus(newStatus);
}
- emit theGlobalStatusChanged(newStatus);// emit signal always because of input ports and sequences definitions.
+ Q_EMIT theGlobalStatusChanged(newStatus);// Q_EMIT signal always because of input ports and sequences definitions.
}
//////////////////
YDFXGUIInputPortValueEditor *childc(qobject_cast<YDFXGUIInputPortValueEditor *>(child));
if(childc)
{
- emit childc->changeLook();
+ Q_EMIT childc->changeLook();
}
}
}
bool step1(_in->isOK() && _out->isOK());
if(!step1)
{
- emit sequencesCanBeDefinedSignal(false);
- emit canBeExecutedSignal(false);
+ Q_EMIT sequencesCanBeDefinedSignal(false);
+ Q_EMIT canBeExecutedSignal(false);
return ;
}
- emit sequencesCanBeDefinedSignal(true);
- emit canBeExecutedSignal(_in->areSeqWellDefined());
+ Q_EMIT sequencesCanBeDefinedSignal(true);
+ Q_EMIT canBeExecutedSignal(_in->areSeqWellDefined());
}
//
// Author : Anthony Geay (EDF R&D)
+#include "YDFXGUIPyThreadSaver.hxx"
#include "YDFXGUIPushButtons.hxx"
#include "YDFXGUIWrap.hxx"
#include "YDFXGUISeqInit.hxx"
-#include "YDFXGUIPyThreadSaver.hxx"
#include "YDFXGUIHostParametrizer.hxx"
#include "YACSEvalSession.hxx"
if(dial.exec())
{
_state=zeWidget->saveState();
- emit sequenceWellDefined(true);
+ Q_EMIT sequenceWellDefined(true);
}
}
std::fill(_items.begin(),_items.end(),0);
_computationInProgress=true;
_mut.unlock();
- emit somethingChanged();
+ Q_EMIT somethingChanged();
}
void YDFXGUIRunInfo::endComputation()
_mut.lock();
_computationInProgress=false;
_mut.unlock();
- emit somethingChanged();
+ Q_EMIT somethingChanged();
}
void YDFXGUIRunInfo::sampleOK(int pos)
_mut.lock();
_items[pos]=1;
_mut.unlock();
- emit somethingChanged();
+ Q_EMIT somethingChanged();
}
void YDFXGUIRunInfo::sampleKO(int pos)
_mut.lock();
_items[pos]=2;
_mut.unlock();
- emit somethingChanged();
+ Q_EMIT somethingChanged();
}
std::vector<char> YDFXGUIRunInfo::getItems() const
#ifndef __YDFXGUIPYTHREADSAVER_HXX__
#define __YDFXGUIPYTHREADSAVER_HXX__
+#include "Python.h"
+
#include "ydfxwidgetsExport.hxx"
-#include "Python.h"
class QThread;
//
// Author : Anthony Geay (EDF R&D)
+#include "Python.h"
#include "YDFXGUISeqInit.hxx"
#include <QFile>
#include <QFileDialog>
#include <QApplication>
-#include "Python.h"
#include "AutoGIL.hxx"
//
if(_fileName.isEmpty())
{
- emit problemDetected(QString("For \"%1\" : no file defined !").arg(zeBossc->getName()));
+ Q_EMIT problemDetected(QString("For \"%1\" : no file defined !").arg(zeBossc->getName()));
return false;
}
QFile file(_fileName);
double v(line2.toDouble(&isOK));
if(!isOK)
{
- emit problemDetected(QString("For \"%1\" : At line %2 it is not a float !").arg(zeBossc->getName()).arg(i));
+ Q_EMIT problemDetected(QString("For \"%1\" : At line %2 it is not a float !").arg(zeBossc->getName()).arg(i));
return false;
}
_vect.push_back(v);
AutoPyRef code(Py_CompileString(txt.c_str(),TMP_FILENAME, Py_file_input));
if(code.get() == NULL)
{
- emit problemDetected(QString("For \"%1\" : python code is invalid !").arg(zeBossc->getName()));
+ Q_EMIT problemDetected(QString("For \"%1\" : python code is invalid !").arg(zeBossc->getName()));
return false;
}
AutoPyRef context(PyDict_New());
PyDict_SetItemString( context, "__builtins__", PyEval_GetBuiltins() );
- AutoPyRef res(PyEval_EvalCode((PyCodeObject *)code.get(), context, context));
+ AutoPyRef res(PyEval_EvalCode(code.get(), context, context));
PyObject *item(PyDict_GetItemString(context,name.c_str()));
//
if(!item)
{
- emit problemDetected(QString("For \"%1\" : Py var %1 is not defined !").arg(zeBossc->getName()));
+ Q_EMIT problemDetected(QString("For \"%1\" : Py var %1 is not defined !").arg(zeBossc->getName()));
return false;
}
if(!PyList_Check(item))
{
- emit problemDetected(QString("For \"%1\" : Py var %1 must be a list !").arg(zeBossc->getName()));
+ Q_EMIT problemDetected(QString("For \"%1\" : Py var %1 must be a list !").arg(zeBossc->getName()));
return false;
}
sz=PyList_Size(item);
PyObject *val(PyList_GetItem(item,i));
if(!PyFloat_Check(val))
{
- emit problemDetected(QString("For \"%1\" : At pos %2 of python list, it is not a float !").arg(zeBossc->getName()).arg(i));
+ Q_EMIT problemDetected(QString("For \"%1\" : At pos %2 of python list, it is not a float !").arg(zeBossc->getName()).arg(i));
return false;
}
_vect[i]=PyFloat_AS_DOUBLE(val);
QVBoxLayout *verticalLayout(new QVBoxLayout(this));
_textEdit=new YDFXGUISeqSetterT(this); verticalLayout->addWidget(_textEdit);
_push=new YDFXGUISeqSetterP(this); verticalLayout->addWidget(_push);
- _textEdit->setText(QString("import math\n%1=[math.sqrt(float(elt)+0.) for elt in xrange(4)]").arg(name));
+ _textEdit->setText(QString("import math\n%1=[math.sqrt(float(elt)+0.) for elt in range(4)]").arg(name));
_textEdit->hide();
_push->hide();
}
connect(_combo,SIGNAL(currentIndexChanged(int)),this,SLOT(typeOfAssignmentChanged(int)));
horizontalLayout->addWidget(_setter);
_combo->setCurrentIndex(0);
- emit _combo->currentIndexChanged(0);//to be sure to sync widgets
+ Q_EMIT _combo->currentIndexChanged(0);//to be sure to sync widgets
}
void YDFXGUISeqLine::loadState(const QMap<QString,QString>& state)
{
int sz;
bool verdict(checkConsistency(sz));
- emit configurationIsOK(verdict);
+ Q_EMIT configurationIsOK(verdict);
}
void YDFXGUISeqInitEff::applyOnEFX()
refSz=locSz;
if(locSz!=refSz)
{
- emit line->setter()->problemDetected(QString("Var %1 does not have the same number of elts than others !").arg(line->getName()));
+ Q_EMIT line->setter()->problemDetected(QString("Var %1 does not have the same number of elts than others !").arg(line->getName()));
return false;
}
}
void YACSEvalYFXWrap::unlockAll()
{
_efx->unlockAll();
- emit lockSignal(false);
+ Q_EMIT lockSignal(false);
}
void YACSEvalYFXWrap::lockPortsForEvaluation()
_efx->lockPortsForEvaluation(inps2,outps2);
_efx->giveResources();//do not remove this line to generate resource info
if(!lockedOrNot)
- emit lockSignal(true);
+ Q_EMIT lockSignal(true);
}
int YACSEvalYFXWrap::getNbOfItems() const
void YACSEvalYFXWrap::setRunningStatus(bool status)
{
if(_isRunning!=status)
- emit runSignal(status);
+ Q_EMIT runSignal(status);
_isRunning=status;
}
if(_isSeqOfValsSet!=newStatus)
{
_isSeqOfValsSet=newStatus;
- emit sequencesAreSetSignal(_isSeqOfValsSet);
+ Q_EMIT sequencesAreSetSignal(_isSeqOfValsSet);
}
}