Querría utilizar getopt
para obtener input from command line argument (entradas desde argumentos de línea de comandos):
import getopt
import sys
version = '1.0'
verbose = False
output_filename = 'default.out'
print('ARGV :', sys.argv[1:])
options, remainder = getopt.gnu_getopt(sys.argv[1:], 'o:v', ['output=',
'verbose',
'version=',
])
Pero cuando ejecuto python convert.py -i [input file name]
obtengo el siguiente error:
GetoptError: option -f not recognized
¿Cuál podría ser el problema?
El objetivo final es utilizar este código para convertir ficheros .csv
en archivos .xes
:
import sys
import getopt
import logging
import getpass
from xml.etree.ElementTree import Element, SubElement, tostring, Comment, ElementTree
from xml.dom import minidom
import csv
from datetime import datetime
def prettify(elem):
rough_string = tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml()
def parse_time(time):
time = datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
return datetime.strftime(time.astimezone(), '{}%z'.format(time.isoformat(timespec='milliseconds')))
def parse_csv(file):
if file.split('.')[-1] != 'csv':
logging.error("file format error")
exit(1)
with open(file, 'r', encoding='utf-8', newline='') as csvfile:
reader = csv.reader(csvfile, strict=True)
for row in reader:
if reader.line_num != 1:
if not row[0] in instances:
instances[row[0]] = [row[1:]]
else:
instances[row[0]].append(row[1:])
def parse_header(root):
extensions = [Element('extension', {
'name': 'Concept',
'prefix': 'concept',
'url': 'http://www.xes-standard.org/concept.xesext'
}), Element('extension', {
'name': 'Time',
'prefix': 'time',
'url': 'http://www.xes-standard.org/time.xesext'
}), Element('extension', {
'name': 'Organizational',
'prefix': 'org',
'url': 'http://www.xes-standard.org/org.xesext'
}), Element('extension', {
'name': 'Lifecycle',
'prefix': 'lifecycle',
'url': 'http://www.xes-standard.org/lifecycle.xesext'
})
]
global_trace = Element('global', {'scope': 'trace'})
global_trace.append(Element('string', {'key': 'concept:name', 'value': 'unknown'}))
global_event = Element('global', {'scope': 'event'})
global_event_attrs = [ Element('string', {'key': 'concept:instance', 'value': 'unknown'}),
Element('string', {'key': 'concept:name', 'value': 'unknown'}),
Element('date', {'key': 'time:timestamp', 'value': '1970-01-01T00:00:00.000+08:00'}),
Element('string', {'key': 'lifecycle:transition', 'value': 'unknown'}),
Element('int', {'key': 'duration', 'value': '0'}),
Element('string', {'key': 'org:role', 'value': 'unknown'}),
Element('string', {'key': 'org:resource', 'value': 'unknown'})
]
global_event.extend(global_event_attrs)
globals = [global_trace, global_event]
classifiers = [
Element('classifier', {'name': 'Activity', 'keys': 'concept:name'}),
# Element('classifier', {'name': 'Activity and Transition', 'keys': 'concept:name lifecycle:transition'})
]
strings = [
Element('string', {'key': 'concept:name', 'value': 'EIS2018-HW1'}),
Element('string', {'key': 'creator', 'value': username})
]
root.append(Comment('Generated by csv2xes'))
root.extend(extensions)
root.extend(globals)
root.extend(classifiers)
root.extend(strings)
if __name__ == '__main__':
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s', level=logging.DEBUG)
if len(sys.argv) == 1:
logging.error('parameter error')
exit(1)
input_file = ''
opts, args = getopt.getopt(sys.argv[1:], 'hi:')
for op, value in opts:
if op == '-i':
input_file = value
else:
exit(1)
username = getpass.getuser()
instances = dict()
log = Element('log', {'xes.version': '2.0', 'xmlns': 'http://www.xes-standard.org'})
parse_header(log)
parse_csv(input_file)
count = 0
for instance in instances.items():
trace = SubElement(log, 'trace')
trace.append(Element('string', {'key': 'concept:name', 'value': instance[0]}))
for element in instance[1]:
start_event = Element('event')
# complete_event = Element('event')
start_attrs = [
Element('string', {'key': 'concept:instance', 'value': str(count)}),
Element('string', {'key': 'concept:name', 'value': element[4]}),
Element('date', {'key': 'time:timestamp', 'value': parse_time(element[1])}),
Element('string', {'key': 'lifecycle:transition', 'value': 'start'}),
Element('int', {'key': 'duration', 'value': element[3]}),
Element('string', {'key': 'org:role', 'value': element[5]}),
Element('string', {'key': 'org:resource', 'value': element[0]})
]
'''
complete_attrs = [
Element('string', {'key': 'concept:instance', 'value': str(count)}),
Element('string', {'key': 'concept:name', 'value': element[4]}),
Element('date', {'key': 'time:timestamp', 'value': parse_time(element[2])}),
Element('string', {'key': 'lifecycle:transition', 'value': 'complete'}),
Element('int', {'key': 'duration', 'value': element[3]}),
Element('string', {'key': 'org:role', 'value': element[5]}),
Element('string', {'key': 'org:resource', 'value': element[0]})
]
'''
start_event.extend(start_attrs)
# complete_event.extend(complete_attrs)
trace.append(start_event)
# trace.append(complete_event)
count += 1
elementTree = ElementTree(element=log)
elementTree.write('{}.xes'.format(input_file.split('.')[0]), encoding='utf-8', xml_declaration=True)
# print(prettify(log))
No estoy segura de cómo funciona este código para convertir ficheros, ni por qué tengo que utilizar getopt
. Si alguien tiene una idea de las razones de su uso, ¡me interesa también!.
Además, cualquier cosa que hago, tengo problemas con la getoption error
, también utilizando otros ejemplos de uso de esta función presentados en internet, y no entiendo por qué.
Gracias por su ayuda.
-f
fuera un parámetro permitido. No necesito el código de conversión, sólo qué parámetros usará tu aplicación. Algo "formal" comoconversor.py -f <archivo> [-n <n° elementos]
o cualquier notación informal o explicación como "el parámetro-f
es obligatorio y tras él se indica un archivo, el parámetro-n
es opcional y tras él se indica un número".