[Python-Dev] -z, -i and -m, maybe bug in runpy?
Nick Coghlan
ncoghlan at gmail.com
Wed Jul 25 12:29:39 CEST 2007
Phillip J. Eby wrote:
> At 12:16 AM 7/25/2007 +1000, Nick Coghlan wrote:
>> I've changed the behaviour in r56520 to simply leave the alterations to
>> sys in place when the function terminates. While this is a definite
>> change to the interface (and hence not a candidate for direct
>> backporting), I think the difference is small enough for the 2.5 to 2.6
>> transition.
>
> Your fix is a definite improvement for me, my "run any importable" patch
> is looking a lot better. There's just one problem left, which is that
> runpy is overwriting sys.argv[0] even if it doesn't need to. So, when
> running from a zipfile, sys.argv[0] ends up None, which is wrong.
>
> However, if I ask runpy not to mess with sys, it creates a new module
> namespace to run the code in, bringing me right back to square one
> (i.e., not being run in __main__). Any thoughts?
>
> My fallback at this point would be to add an option to run_module() to
> request that sys.argv[0] be used in place of calling _get_filename().
> It seems ugly to do that, though, if only because there are already so
> many arguments to that function.
Adding a get_filename() method to ZipImporter objects would get you
something better than None in sys.argv[0] (specifically, you would see
<zipfile_name>/__main__.py)
For a reason I mentioned below, another idea I've had is to tweak the
run_module semantics again and state that if __name__ already exists in
sys.modules, then the code will be executed in the existing module,
rather than in a new module (regardless of the value of the alter_sys
argument).
This would mean that the -m switch would always use the builtin __main__
module, instead of creating a new module the way it does now. This would
not only fix your current problem, but also avoid any potential issues
associated with having sys.modules["__main__"] refer to a different
module while the interpreter is starting up (e.g. while running
sitecustomize.py, and while doing any package imports needed to locate
the module to be executed).
I'm actually becoming more and more in favour of reverting run_module
back to its 2.5 semantics and adding a separate function that does the
right thing for the -m switch. It is really starting to look like the
useful behaviour for a module namespace based execfile equivalent and
the -m switch aren't as closely aligned as I thought they were back when
I wrote PEP 338.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://www.boredomandlaziness.org
More information about the Python-Dev
mailing list