how to enable error message in exec??

Quinn Dunkan quinn at retch.ugcs.caltech.edu
Sun Apr 8 18:54:09 EDT 2001


On Sun, 08 Apr 2001 17:00:13 -0000, ed_tsang at yahoo.com <ed_tsang at yahoo.com>
wrote:
>My current script, say script A, need to execute some python code in 
>other file, say script B,  by using exec() function. But if there is 
>any syntax error in script B, the exec() returns, but I would not 
>know what kind of syntax error is that. How can I enable this kind of 
>execution gives the same level of error reporting capability as if 
>the python code is run thorugh in the same file?
>
>
>Code fragment:
>
>execCmd = "guiCb.pixitObj." + eventHandler[0]
>                         
>exec(execCmd)
>
>where execCmd is just a string containing the full execution python 
>code. eventHandler[0] is a python code read from script B.

Firstly, exec isn't a function, it's a statement.  So it has no return value
and doesn't need parens.  If eventHandler[0] is really python code (say,
"print 'hi there'") , your program will try to run

guiCb.pixitOjb.print 'hi there'

which is probably not what you meant.  I'm not sure what that 'guiCb.pixitObj'
is even supposed to do.  But in any case, execed code will throw exceptions
like any other code

try:
    exec eventHandler[0]
execpt:
    exc = sys.exc_info()[0]
    print exc
    # ...

I can't say if 'exec' is a good solution here, but it's probably not :)  If
you're writing event handlers, you probably want to call methods on a
dynamically obtained object (like "get_handler(event).handle(event)").  If you
want to load code from disk, you can load pickled objects or marshalled
bytecode.



More information about the Python-list mailing list