Salome HOME
Merge branch 'master' into V9_merge
[tools/eficas.git] / convert / convert_python.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2007-2021   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 exec
48
49 """
50 from __future__ import absolute_import
51 try :
52     from builtins import str
53     from builtins import object
54 except :
55     pass
56 import sys,traceback
57
58 from .parseur_python import PARSEUR_PYTHON
59 from Noyau import N_CR
60 from Extensions.i18n import tr
61 from Extensions.eficas_exception import EficasException
62
63 def entryPoint():
64     """
65         Retourne les informations necessaires pour le chargeur de plugins
66         Ces informations sont retournees dans un dictionnaire
67     """
68     return {
69          # Le nom du plugin
70            'name' : 'python',
71          # La factory pour creer une instance du plugin
72            'factory' : Pythonparser,
73            }
74
75
76 class Pythonparser(object):
77     """
78         Ce convertisseur lit un fichier au format python avec la
79         methode readfile : convertisseur.readfile(nom_fichier)
80         et retourne le texte au format outformat avec la
81         methode convertisseur.convert(outformat)
82
83         Ses caracteristiques principales sont exposees dans 2 attributs
84         de classe :
85            - extensions : qui donne une liste d'extensions de fichier preconisees
86            - formats : qui donne une liste de formats de sortie supportes
87     """
88     # Les extensions de fichier preconisees
89     extensions=('.py',)
90     # Les formats de sortie supportes (eval dict ou exec)
91     # Le format exec est du python executable (commande exec) converti avec PARSEUR_PYTHON
92     # Le format execnoparseur est du python executable (commande exec) non converti
93     formats=('exec','execnoparseur')
94
95     def __init__(self,cr=None):
96         # Si l'objet compte-rendu n'est pas fourni, on utilise le
97         # compte-rendu standard
98         self.text=''
99         if cr :
100             self.cr=cr
101         else:
102             self.cr=N_CR.CR(debut='CR convertisseur format python',
103                             fin='fin CR format python')
104
105     def readfile(self,filename):
106         self.filename=filename
107         try:
108             with open(filename) as fd :
109                 self.text=fd.read()
110         except:
111             self.cr.exception(tr("Impossible d'ouvrir le fichier %s" ,str(filename)))
112             self.cr.fatal(tr("Impossible d'ouvrir le fichier %s" ,str(filename)))
113             return
114
115     def convert(self,outformat,appliEficas=None):
116         if outformat == 'exec':
117             try:
118                 #import cProfile, pstats, StringIO
119                 #pr = cProfile.Profile()
120                 #pr.enable()
121                 l= PARSEUR_PYTHON(self.text).getTexte(appliEficas)
122
123                 #pr.disable()
124                 #s = StringIO.StringIO()
125                 #sortby = 'cumulative'
126                 #ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
127                 #ps.print_stats()
128                 #print (s.getValue())
129
130                 return l
131             except EficasException:
132                 # Erreur lors de la conversion
133                 l=traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],
134                                              sys.exc_info()[2])
135                 self.cr.exception(tr("Impossible de convertir le fichier Python qui doit contenir des erreurs.\n\
136                                       On retourne le fichier non converti. Prevenir la maintenance.\n\n %s", ''.join(l)))
137                 # On retourne neanmoins le source initial non converti (au cas ou)
138                 return self.text
139         elif outformat == 'execnoparseur':
140             return self.text
141         else:
142             raise EficasException(tr("Format de sortie : %s, non supporte", outformat))
143             return None