[Python-Dev] What about PEP 299?
Nick Coghlan
ncoghlan at gmail.com
Wed Mar 29 14:17:40 CEST 2006
Guido van Rossum wrote:
> On 3/28/06, Charles Cazabon <python at discworld.dyndns.org> wrote:
>> It might be worth instead adding an option flag to the executable that implies
>> "from the loaded module, run __main__() with sys.argv as its argument(s)", so
>> the user can get this behaviour with `python -X somemodule.py`.
>
> You can do "python -x somemodule" as long as somemodule.py uses the if
> __name__=='__main__' convention. What does your proposal add?
FWIW, you can already (Python 2.4) do something like:
------- x.py ---------
import sys
if __name__ == __main__:
del sys.argv[0] # Get rid of reference to ourselves
mod_name = sys.argv[0] # First arg is now module to be run
mod = __import__(mod_name) # Run the top level module code
main = mod.__main__ # Grab the main function
sys.modules["__main__"] = mod # Make that module the __main__ one
try:
sys.argv[0] = mod.__file__ # Try to set argv[0] properly
except AttributeError:
pass
sys.exit(main(*sys.argv)) # Run the function
-------------------------
Put that in site-packages and "python -mx somemodule" will do exactly as
Charles describes.
Getting it to work with a filename instead of a module name would be a bit
trickier, but not a lot.
However, I think PEP 299 is mainly a holdover from C/C++/Java where the top
level of a module is a play area for the compiler that the runtime never
really gets to see. I know I found PEP 299 appealing when I first seriously
started using Python, but the appeal faded over time as I got used to the idea
of being able to have control logic at the top level of a module (to the point
where the idea is now thoroughly *un*appealing).
PEP 299's other 'use case' (trying to run another program's main function from
within the current program) seems like a recipe for disaster - far better to
use the subprocess module instead (since, strangely enough, application
initialisation code has this tendency to assume it has sole control of the
interpreter).
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://www.boredomandlaziness.org
More information about the Python-Dev
mailing list