开发者

imports while starting an interactive shell

开发者 https://www.devze.com 2022-12-18 15:50 出处:网络
When I start the interactive django shell through manage.py, by executing python -v manage.py shell from the project directory, I see a lot of modules of format django.package.module getting impor

When I start the interactive django shell through manage.py, by executing

python -v manage.py shell

from the project directory, I see a lot of modules of format django.package.module getting imported in the verbose output but still I have to import them to use it in the shell.

The same happens when I just run the Python shell (with the -v argument). For example I see this in the verbose output,

import os # precompiled from /usr/local/gdp/lib/python2.4/os.pyc

but still i have to do import os to import and use the os module. What is being imported that am seeing in the verbose output and why I have to import them explicitly again to use them 开发者_Go百科in the shell? Does Python load some essential modules while starting the shell or is it some kind of behind-the-scene magic?


-v traces the first import of a module -- the one that actually loads the module (executes its code, and so may take a bit of time) and sticks it into sys.modules.

That has nothing to do whether your interactive session (module __main__) gets the module injected into its namespace, of course. To ensure module 'goo' does get into the namespace of module 'X' (for any X, so of course including __main__... among many, many others), module 'X' just needs to import goo itself (a very fast operation indeed, if sys.modules['goo'] is already defined!-).


Python loads the site module implicitly when starting up, which may in turn import other modules for its own use. You can pass -S to disable this behavior.


They are getting imported (look at sys.modules) and references to the module are created in whichever modules have imported it.

When you do an import in your shell, if the module has already been imported, you will just get a copy of the reference to it in sys.modules

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号