Think the title summarizes the question :-)
A Python script is a collection of commands in a file designed to be executed like a program. The file can of course contain functions and import various modules, but the idea is that it will be run or executed from the command line or from within a Python interactive shell to perform a specific task.
What are modules in Python? Modules refer to a file containing Python statements and definitions. A file containing Python code, for example: example.py , is called a module, and its module name would be example . We use modules to break down large programs into small manageable and organized files.
The main difference between both is scripting languages don't require any compilation and are directly interpreted. The compiled codes execute faster than the interpreted codes as they are changed in to a native machine program.
Library : It is a collection of modules. (Library either contains built in modules(written in C) + modules written in python). Module : Each of a set of standardized parts or independent units that can be used to construct a more complex structure.
A script is generally a directly executable piece of code, run by itself. A module is generally a library, imported by other pieces of code.
Note that there's no internal distinction -- both are executable and importable, although library code often won't do anything (or will just run its unit tests) when executed directly and importing code designed to be a script will cause it to execute, hence the common if __name__ == "__main__"
test.
Any Python module may be executed as a script. The only significant difference is that when imported as a module the filename is used as the basis for the module name whereas if you execute it as a script the module is named __main__
.
This distinction makes it possible to have different behaviour when imported by enclosing script specific code in a block guarded by if __name__=="__main__"
. This has been known to cause confusion when a user attempts to import the main module under its own name rather than importing __main__
.
A minor difference between scripts and modules is that when you import a module the system will attempt to use an existing .pyc file (provided it exists and is up to date and for that version of Python) and if it has to compile from a .py file it will attempt to save a .pyc file. When you run a .py file as script it does not attempt to load a previously compiled module, nor will it attempt to save the compiled code. For this reason it may be worth keeping scripts small to minimise startup time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With