When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special
__name__ variable to have a value
"__main__". If this file is being imported from another module,
__name__ will be set to the module’s name.
In the case of your script, let’s assume that it’s executing as the main function, e.g. you said something like
on the command line. After setting up the special variables, it will execute the
import statement and load those modules. It will then evaluate the
def block, creating a function object and creating a variable called
myfunction that points to the function object. It will then read the
if statement and see that
"__main__", so it will execute the block shown there.
One of the reasons for doing this is that sometimes you write a module (a
.py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.
The simplest explanation for the
__name__ variable (imho) is the following:
Create the following files.
print "Hello World from %s!" % __name__
if __name__ == '__main__':
print "Hello World again from %s!" % __name__
Running them will get you this output:
$ python a.py
Hello World from b!
As you can see, when a module is imported, Python sets
globals()['__name__'] in this module to the module’s name.
$ python b.py
Hello World from __main__!
Hello World again from __main__!
As you can see, when a file is executed, Python sets
globals()['__name__'] in this file to
Python PYC :-
As an important speed-up of the start-up time for short programs that use a lot of standard modules, if a file called spam.pyc exists in the directory where spam.py is found, this is assumed to contain an already-“byte-compiled” version of the module spam. The modification time of the version of spam.py used to create spam.pyc is recorded in spam.pyc, and the .pyc file is ignored if these don’t match.
See the ref for more info. But some specific answers:
The contents of the spam.pyc file are platform independent, so a Python module directory can be shared by machines of different architectures.
It’s not an executable; it’s used internally by the compiler as an intermediate step.
In general, you don’t make .pyc files by hand: the interpreter makes them automatically.