[Idle-dev] Modifying ScriptBinding.run_script_event to automatically modify sys.path?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 22 Jan 2002 17:58:54 -0800 (PST)


Hi everyone,

A while back, I sent a patch to automagically add a script's directory
path to sys.path.  Here's a link to the original post:

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


The problem is this: if a user is experimenting with importing their own
modules, they run into an ImportError because their modules aren't located
in the system path.

This is somewhat weird to me, as I would have expected IDLE to do this for
me.  I've isolated the code to run_script_event(), which uses an
execfile() call.  execfile() doesn't extend sys.path, probably for
security reasons.  But for someone running scripts through IDLE, this
seems a bit paranoid.

Here's a modified run_script_even that temporarily adjusts sys.path, just
long enough for the run_script command to finish:

####
def run_script_event(self, event):
    filename = self.getfilename()
    if not filename:
        return

    flist = self.editwin.flist
    shell = flist.open_shell()
    interp = shell.interp
    if (not sys.argv or
        os.path.basename(sys.argv[0]) != os.path.basename(filename)):
        # XXX Too often this discards arguments the user just set...
        sys.argv = [filename]
    old_syspath = sys.path[:]
    sys.path.append(os.path.dirname(os.path.abspath(filename)))
    interp.execfile(filename)
    sys.path = old_syspath
###


Does this seem like a reasonable thing to add to IDLE?  I always feel very
worried about telling new Python programmers to edit their PYTHONPATH...  
*grin*