How do I exec a user script and note errors?
Fredrik Lundh
fredrik at pythonware.com
Wed Dec 18 18:14:34 EST 2002
Robert Ferrell wrote:
> I want to read in (and execute) a user python file. I know I can do
> that with execfile(). However, I want to catch some errors that the
> user might have made. If I read the file line at a time, and exec
> each line, I can use try:/except:. However, that doesn't work if the
> user has function defitions, or other multi-line code blocks in the
> file.
how about:
try:
execfile(filename)
except:
...
if you really want to process the file a line at a time, you can use
the InteractiveConsole module from the code module:
from code import InteractiveConsole
program = [
"print 'spam'\n",
"for i in range(10):\n",
" print 'bacon'\n",
"print 'egg'\n",
]
console = InteractiveConsole()
for line in program:
print "--- push", repr(line)
console.push(line)
print "--- done"
</F>
More information about the Python-list
mailing list