import sys
from sys import argv
I read about about import statement in pydocs. It says it executes in two steps. (1)find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). The first form (without from) repeats these steps for each identifier in the list
. The form with from performs step (1) once, and then performs step (2) repeatedly.
Here I understood that in first case sys
module will be initialized as part of 1st step and then it will be made available to local namespace as 2nd step.
But what will happen in case of second import form?
Will sys
module be initialized as first step and only argv
function of sys
module(NO OTHER function) is made available to local namespace.
Because I am not able to call any other functions of sys
module when I am using second form of import statement. So just want to clarify on it specifically. As if sys
module has been initialized in from import statement then we should be able to call other functions using sys
. But that is not working.
#import sys
from sys import argv
script, input = argv
print "This was the input entered by command line", input
print sys.path # this is not working giving error name sys is not defined.
I am suspecting in case of from import statement sys
module is not getting initalized, only argv
function is getting initialized but in that case what does from step performs step(1) once mean pydocs?(Note: I am working on python 2.7)
The import statement always initializes the whole module. The modules are stored in the
sys.modules
dictionary.When you use
from sys import argv
thesys
module is not bound locally, onlyargv
is. You cannot use the namesys
in your module, because you didn't import that name.You can only reach the
sys
module if you importedsys
separately:And you can always access all imported modules by accessing
sys.modules
:Here I bound the name
modules
to thesys.modules
dictionary, and through that reference, find thesys
module, and reference thepath
attribute.Demo: