4. Debugging

All output from the python interpreter goes right now to the standard output/error of cssed. This difficults debugging as you need to start cssed from a console to catch the python backtrace if the script fails.

When a script fails, cssed will warn you about this failure but will not get further information about what failed or how it failed.

You can use python facilities to get a backtrace. It may work some times. Here is an example on how to get a backtrace on a cssed script.

import cssed
import sys
import traceback

def printerr():
	trace = ""
	exception = ""
	exc_list = traceback.format_exception_only (sys.exc_type, sys.exc_value)
	for entry in exc_list:
		exception += entry
	tb_list = traceback.format_tb(sys.exc_info()[2])
	for entry in tb_list:
		trace += entry	
	cssed.error_message("%s\n%s" % (exception, trace), "Script Error")

	# this will fail
	# notify this failure to the interpreter

You can also redirect standard input and error to cssed, an pygtk window, or to your preferred location.

import gtk
import cssed
import sys

# a simple class with a write method
class WritableTextView:
    def __init__(self, textview):
        self.textview = textview
    def write(self, string):		
        buffer = self.textview.get_buffer()
        iter = buffer.get_end_iter()
class ViewStdoutDialog:
	def delete_event(self, widget, event, data=None):
		sys.stdout = sys.__stdout__
		sys.stderr = sys.__stderr__
		return gtk.TRUE

	def button_close_clicked_cb (self, widget, data=None):
		self.delete_event(self.dialog, None)

	def __init__(self):		
		self.dialog = gtk.Dialog()	
		self.dialog.connect("delete_event", self.delete_event)
		# model and tree
		self.textview = gtk.TextView();
		self.scrolledwindow = gtk.ScrolledWindow()
		button_close = gtk.Button ("Close")
		button_close.connect("clicked", self.button_close_clicked_cb)
		self.writable = WritableTextView(self.textview)
		sys.stdout = self.writable 
		sys.stderr = self.writable 

Other easier way to get this output is to launch a cssed instance from a console and watch to the python backtrace.

Note: Even while it may look bad and complex, to start a new cssed instance from a console to test the script, it's the recommended method to do it. The script can do weird things with your working instance of cssed, such as halt it or close it - as when calling gtk.main_quit() or sys.exit() by mistake - so to risk a new instance of cssed may be a good way to avoid to reopen our working instance - if something goes wrong - or to avoid to loose your work, if you forgot to save anything and the script halts cssed.

It's also the preferred method to test cssed plugins.