[Tutor] Trapping exceptions in batch scripts

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 6 Jan 2002 15:16:51 -0800 (PST)


On Sun, 6 Jan 2002, Charlie Clark wrote:

> There seems to be two ways of actually running a script either by
> importing it or by using execfile Import has to be called via
> __import__ as it is not possible to pass a variable to import.

I don't think __import__ is a good approach, expecially because if your
scripts use the 'if __name__ == "__main__"' idiom, they won't execute
during a module import.



> This seems somewhat clumsy but when I tried execfile I got some
> confusing error messages claiming that names weren't properly defined.
> The scripts themselves ran fine but occasionally produced name errors
> when run using execfile.

The problem is that when we use execfile(), Python doesn't include that
file's directory within 'sys.path'.  If your script does any 'import'ing,
Python won't look at that file's directory when searching for modules.


In fact, IDLE's "Run Script" command suffers from the exact same problem;
I posted a fix to it:

    http://mail.python.org/pipermail/tutor/2001-December/010915.html



You can use something similar:

###
def my_execfile(filename):
    old_syspath = sys.path[:]
    sys.path.append(os.path.dirname(os.path.abspath(filename)))
    execfile(filename)
    sys.path = old_syspath
###


This my_execfile() may behave more nicely because it includes the
directory of the script within sys.path, so that if the script uses
'import', it behaves the way you probably want it to.

Good luck to you!