[issue10129] Curious 'name not defined error' with 'python -m'

Georg Brandl report at bugs.python.org
Sun Oct 17 08:03:11 CEST 2010


Georg Brandl <georg at python.org> added the comment:

(This is not specific to running with -m, it occurs as well when you do "python a.py b.py".)

The issue here is your call to exec() does not execute the code as its own module.  It executes the code as part of the main() function in a.py, with (since you don't give a global namespace argument) the same global namespace as that of a.main(), and there is no "sys" in that namespace.  Further, the compiler cannot treat b.main like a nested function of a.main (which would then create a closure over the "sys" imported inside a.main).  Therefore, the reference to sys is treated as a global and not found.

If you give the exec() function an explicit dictionary as the globals argument, this "works":

def main():
    d = {'__name__': '__main__'}
    exec(compile(open(sys.argv[1]).read(), sys.argv[1], 'exec'), d)

----------
nosy: +georg.brandl
resolution:  -> wont fix
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue10129>
_______________________________________


More information about the Python-bugs-list mailing list