-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseit.py
258 lines (210 loc) · 9.48 KB
/
parseit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Patricio Moracho <pmoracho@gmail.com>
#
# parseit
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 3 of the GNU General Public License
# as published by the Free Software Foundation. A copy of this license should
# be included in the file GPL-3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
__author__ = "Patricio Moracho <pmoracho@gmail.com>"
__appname__ = "parseit"
__appdesc__ = "Parseador de archivos"
__license__ = 'GPL v3'
__copyright__ = "2016, 2017 %s" % (__author__)
__version__ = "1.4.2"
__date__ = "2016/10/17"
"""
###############################################################################
# Imports
###############################################################################
"""
try:
import sys
import os
import gettext
import tempfile
from rparser import Parser
"""
Librerias adicionales
"""
def my_gettext(s):
"""my_gettext: Traducir algunas cadenas de argparse."""
current_dict = {
'usage: ': 'uso: ',
'optional arguments': 'argumentos opcionales',
'show this help message and exit': 'mostrar esta ayuda y salir',
'positional arguments': 'argumentos posicionales',
'the following arguments are required: %s': 'los siguientes argumentos son requeridos: %s',
'show program''s version number and exit': 'Mostrar la versión del programa y salir',
'expected one argument': 'se espera un valor para el parámetro',
'expected at least one argument': 'se espera al menos un valor para el parámetro'
}
if s in current_dict:
return current_dict[s]
return s
gettext.gettext = my_gettext
import argparse
except ImportError as err:
modulename = err.args[0].split()[3]
print("No fue posible importar el modulo: %s" % modulename)
sys.exit(-1)
##################################################################################################################################################
# Inicializar parametros del programa
##################################################################################################################################################
def init_argparse():
usage = '\nEjemplos de uso:\n\n' \
'- Interpretar un archivo infiriendo el formato:\n' \
' %(prog)s [opciones] <archivo a interpretar>\n\n' \
'- Mostrar todos los formatos disponibles y sus definiciones:\n' \
' %(prog)s [opciones] -s [opciones]\n\n' \
'- Mostrar esta ayuda:\n' \
' %(prog)s -h\n\n'
cmdparser = argparse.ArgumentParser(
prog=__appname__,
description="%s\n%s\n" % (__appdesc__, __copyright__),
epilog=usage,
formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=35),
usage=None
)
cmdparser.add_argument('inputfile', type=str, nargs='?', help="Archivo de input", metavar="\"archivo a interpretar\"")
cmdparser.add_argument("-v", "--version", action='version', version=__version__)
cmdparser.add_argument('-f', '--format', type=str, action="store", dest="formato", help="Definir path o archivo FMT a utilizar", metavar="\"path o archivo\"")
cmdparser.add_argument('-u', '--useformat', type=str, action="store", dest="useformat", help="Forzar el uso de un determinado formato para porcesar el archivo", metavar="\"formato\"")
cmdparser.add_argument('-t', '--dontusetables', action="store_true", dest="dontusetables", help="No usar traducción por tablas y mostrar los datos nativos")
cmdparser.add_argument('-s', '--showformat', action="store_true", dest="showformat", help="Mostrar información de un formato (--format) en particular o todos los definidos")
cmdparser.add_argument('-i', '--ignorefmterror', action="store_true", dest="ignorefmterror", help="Ignorar errores al cargar archivos de formatos")
cmdparser.add_argument('-o', '--outputfile', action="store", dest="outputfile", help="Exportar a un archivo", metavar="\"archivo\"")
cmdparser.add_argument('-x', '--openfile', action="store_true", dest="openfile", help="abrir automáticamente el archivo")
cmdparser.add_argument('-e', '--exportformat', action="store", dest="exportformat", help="Exportar en un formato específico", metavar="\"formato\"", default="psql")
cmdparser.add_argument('-c', '--showcols', type=str, action="store", dest="showcols", help=u"Números de las columnas a mostrar", metavar="\"columnas\"")
cmdparser.add_argument('-r', '--showrows', type=str, action="store", dest="showrows", help=u"Números de las filas a mostrar", metavar="\"filas\"")
cmdparser.add_argument('-n', '--dontshowrecordnumber', action="store_false", dest="addrecordnumber", help="No mostrar los números de cada registro")
cmdparser.add_argument('-z', '--horizontalmode', action="store_true", dest="horizontalmode", help="Modo de visualización horizontal")
cmdparser.add_argument('-a', '--addtotals', action="store_true", dest="addtotals", help="Agregar una última fila con los totales de los campos númericos")
cmdparser.add_argument('-l', '--css-file', action="store", dest="cssfile", help="Archivo de estilos (.Css) para la salida Html", metavar="\"archivo css\"")
cmdparser.add_argument('-b', '--search-text', type=str, action="store", dest="searchtext", help="Búsqueda y filtrado de texto", metavar="\"Texto a buscar\"")
cmdparser.add_argument('-d', '--no-header', action="store_true", dest="noheader", help="No mostrar el encabezado de columnas")
return cmdparser
def showerror(msg):
print("\n!!!! %s error: %s\n" % (__appname__, msg))
def resource_path(relative):
"""Obtiene un path, toma en consideración el uso de pyinstaller"""
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative)
return os.path.join(relative)
def expand_filename(filename):
if '{desktop}' in filename:
print(filename)
tmp = os.path.join(os.path.expanduser('~'), 'Desktop')
print(tmp)
filename = filename.replace('{desktop}', tmp)
if '{tmpdir}' in filename:
tmp = tempfile.gettempdir()
filename = filename.replace('{tmpdir}', tmp)
if '{tmpfile}' in filename:
tmp = tempfile.mktemp()
filename = filename.replace('{tmpfile}', tmp)
return filename
def parsefile(parser, args, formato):
parser.dontusetables = args.dontusetables
parser.addrecordnumber = args.addrecordnumber
parser.addtotals = args.addtotals
parser.cssfile = args.cssfile
parser.openfile = args.openfile
parser.searchtext = args.searchtext
if args.outputfile:
parser.outputfile = expand_filename(args.outputfile)
parser.parseit_as(formato)
parser.export(args.exportformat, args.showcols, args.showrows, args.horizontalmode, args.noheader)
##################################################################################################################################################
# Main program
##################################################################################################################################################
if __name__ == "__main__":
cmdparser = init_argparse()
try:
args = cmdparser.parse_args()
except IOError as msg:
cmdparser.error(str(msg))
sys.exit(-1)
"""
O se muestran los formatos o se procesa un archivo
"""
if not args.showformat and not args.inputfile:
cmdparser.error("Se debe indicar alguna opción válida -s/--showformat o \"archivo a interpretar\"\n")
sys.exit(-1)
# Definir el path de dónde obtener la configuración
if not args.formato:
# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
application_path = os.path.dirname(sys.executable)
elif __file__:
application_path = os.path.dirname(__file__)
# print("basedir : {0}".format(application_path))
default_fmt_file = 'parseit.fmt'
fmtpath = resource_path(os.path.join(application_path, default_fmt_file))
else:
fmtpath = args.formato
try:
parser = Parser(fmtpath, args.ignorefmterror)
except Exception as e:
showerror(e)
sys.exit(-1)
if args.showformat:
if args.useformat:
# Se muestra el formato solictado
parser.showformats(args.useformat)
sys.exit(0)
if args.inputfile:
parser.set_file_to_parse(args.inputfile)
posibles = []
try:
posibles = parser.get_posible_formats()
except Exception as e:
pass
if len(posibles) == 1:
# Se muestra el formato del archivo de entrada
formato = posibles[0]
parser.showformats(formato)
else:
# No se pudo identificar el formato se muestran todos
parser.showformats()
else:
# No se indico ni formato ni inputfile -> se muestran todos los
# formatos
parser.showformats()
sys.exit(0)
if args.inputfile:
parser.set_file_to_parse(args.inputfile)
try:
posibles = parser.get_posible_formats()
except Exception as e:
showerror(e)
sys.exit(-1)
if len(posibles) == 1:
formato = posibles[0]
else:
if not args.useformat:
showerror("Debe seleccionar el formato del archivo ya que no ha sido posible identificarlo. Los posibles formatos son: {0}\n".format(posibles))
cmdparser.print_help()
sys.exit(-1)
else:
formato = args.useformat
"""
Parseo finalmente el archivo
"""
try:
parsefile(parser, args, formato)
except Exception as e:
showerror(e)
sys.exit(-1)
sys.exit(0)