Salome HOME
98a6faabd9cffa1f4440889e0dd4a4b64e65467a
[tools/eficas.git] / convert / convert_pyth.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2007-2013   EDF R&D
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20 """
21     Ce module contient le plugin convertisseur de fichier
22     au format python pour EFICAS.
23
24     Un plugin convertisseur doit fournir deux attributs de classe :
25     extensions et formats et deux methodes : readfile,convert.
26
27     L'attribut de classe extensions est une liste d'extensions
28     de fichiers preconisees pour ce type de format. Cette information
29     est seulement indicative.
30
31     L'attribut de classe formats est une liste de formats de sortie
32     supportes par le convertisseur. Les formats possibles sont :
33     eval, dict ou exec.
34     Le format eval est un texte source Python qui peut etre evalue. Le
35     resultat de l'evaluation est un objet Python quelconque.
36     Le format dict est un dictionnaire Python.
37     Le format exec est un texte source Python qui peut etre execute. 
38
39     La methode readfile a pour fonction de lire un fichier dont le
40     nom est passe en argument de la fonction.
41        - convertisseur.readfile(nom_fichier)
42
43     La methode convert a pour fonction de convertir le fichier
44     prealablement lu dans un objet du format passe en argument.
45        - objet=convertisseur.convert(outformat)
46
47     Ce convertisseur supporte le format de sortie dict
48
49 """
50 import sys,string,traceback
51
52 from Noyau import N_CR
53 from Extensions.i18n import tr
54 from Extensions.eficas_exception import EficasException
55
56 def entryPoint():
57    """
58        Retourne les informations necessaires pour le chargeur de plugins
59        Ces informations sont retournees dans un dictionnaire
60    """
61    return {
62         # Le nom du plugin
63           'name' : 'pyth',
64         # La factory pour creer une instance du plugin
65           'factory' : PythParser,
66           }
67
68
69 class PythParser:
70    """
71        Ce convertisseur lit un fichier au format pyth avec la 
72        methode readfile : convertisseur.readfile(nom_fichier)
73        et retourne le texte au format outformat avec la 
74        methode convertisseur.convert(outformat)
75
76        Ses caracteristiques principales sont exposees dans 2 attributs 
77        de classe :
78          - extensions : qui donne une liste d'extensions de fichier preconisees
79          - formats : qui donne une liste de formats de sortie supportes
80    """
81    # Les extensions de fichier preconisees
82    extensions=('.pyth',)
83    # Les formats de sortie supportes (eval dict ou exec)
84    formats=('dict',)
85
86    def __init__(self,cr=None):
87       # Si l'objet compte-rendu n'est pas fourni, on utilise le compte-rendu standard
88       if cr :
89          self.cr=cr
90       else:
91          self.cr=N_CR.CR(debut='CR convertisseur format pyth',
92                          fin='fin CR format pyth')
93       self.g={}
94
95    def readfile(self,filename):
96       self.filename=filename
97       try:
98          self.text=open(filename).read()
99       except:
100          self.cr.fatal(tr("Impossible d'ouvrir le fichier : %s",str( filename)))
101          return
102       self.g={}
103       try:
104          exec self.text in self.g
105       except EficasException as e:
106          l=traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
107          s= string.join(l[2:])
108          s= string.replace(s,'"<string>"','"<%s>"'%self.filename)
109          self.cr.fatal(tr("Erreur a l'evaluation :\n %s", s))
110
111    def convert(self,outformat,appli=None):
112       if outformat == 'dict':
113          return self.getdict()
114       else:
115          raise EficasException(tr("Format de sortie : %s, non supporte", outformat))
116
117    def getdict(self):
118       d={}
119       for k,v in self.g.items():
120          if k[0] != '_':d[k]=v
121       return d