I need use python3 to create a simple tcl parser, so i use tkinter.Tcl to do this.
The parsing works well, but when I want to implement behavior for a parsing failure, I find that I can’t retrieve the information contained in the TclError
that I threw.
Here is my parser code:
import tkinter as tk
from tkinter import Tcl
def default_command_func(*args):
print(f'default_command_func : {args}')
return 'success'
class TclParser(object):
def __init__(self, data_cls) -> None:
self.interp = tk.Tcl()
self.data_cls = data_cls
self.commands = {}
def error_handler(self, error):
if "invalid command name" in str(error):
command_name =str(error).split('"')[1]
return command_name
else:
print(f'parse tcl failed due to: {error}')
return None
def register_tcl_command(self, command_name, command_func):
self.commands[command_name] = command_func
def register_tcl_command_impl(self, command_name, command_func, data_base):
def wrapper(*args):
return command_func(data_base, args)
self.interp.createcommand(command_name, wrapper)
def register_default_command(self, command_name):
self.interp.createcommand(command_name, default_command_func)
def parse_tcl(self, tcl_path, ignore_unknow_command = False):
with open(tcl_path, 'r') as file:
tcl_file = file.read()
stop = False
data_base = None
while not stop:
data_base = self.data_cls()
stop = not ignore_unknow_command
for command_name, command_func in self.commands.items():
self.register_tcl_command_impl(command_name, command_func, data_base)
try:
self.interp.eval(tcl_file)
except tk.TclError as e:
unregistered_command = self.error_handler(e)
if unregistered_command is not None:
print(f"invalid command {unregistered_command}, try register.")
self.register_default_command(unregistered_command)
continue
else:
print(f'unknow error : {str(e)}')
break
break
return data_base
Here is how i parse my tcl file:
def wrapped_cmd(data_base, args):
if "error" in args:
raise tk.TclError("Custom error: Invalid arguments passed")
else:
print(f"Executing custom command with args: {args}")
return "success"
tcl_script = """
custom_cmd arg1 arg2
custom_error error
"""
with open("test.tcl", "w") as f:
f.write(tcl_script)
parser = TclParser(int)
parser.register_tcl_command('custom_cmd', wrapped_cmd)
parser.register_tcl_command('custom_error', wrapped_cmd)
tech = parser.parse_tcl("test.tcl", True)
Then I get message like this:
“””
Executing custom command with args: (‘arg1’, ‘arg2’)
parse tcl failed due to:
unknow error :
“””
My expected output is as follows:
“””
Executing custom command with args: (‘arg1’, ‘arg2’)
parse tcl failed due to: Custom error: Invalid arguments passed
unknow error : Custom error: Invalid arguments passed
“””
heixxxx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.