The usage of -m option of python

Modulok modulok at gmail.com
Mon Mar 18 23:34:21 CET 2013


>> Hi,
>>
>> I don't quite understand how -m option is used. And it is difficult to
>> search for -m in google. Could anybody provide me with an example on
>> how to use this option? Thanks!
>>
>>        -m module-name
>>               Searches sys.path for the named module and runs the
>> corresponding .py file as a script.

> I don't quite understand how -m option is used. And it is difficult to
> search for -m in google. Could anybody provide me with an example on
> how to use this option? Thanks!


Forgive me if I'm too verbose:

When this module is imported via a regular python import statement, the
module's special property ``__name__`` is automatically set to the
name of the module, as a string. For example::

    >>> import random
    >>> random.__name__
    >>> 'random'

If a file is executed as a script from the operating system's command line, the
value of the ``__main__`` property is instead automatically set to the string
"__main__". This is useful because many python modules have a line such as::


    if __name__ == "__main__":
        # Do something different...
        # Maybe run some unit tests or something.
        # Or perhaps parse some command line arguments...

This means you can cd into the python modules directory on your system and
execute one of the built-in modules directly::

    cd /usr/local/lib/python3.3

    python3.3 random.py
        # Tests the random number functions and spits out the result to the
        # console.

We have one file with two behaviors, depending on how it gets executed. You can
use the same concept in your own scripts to have both a command line script
that does something useful, as well as an importable python module to use in
other scripts. Remember, if ``__name__ == "__main__"`` the file is being run as
a script. Otherwise it's being imported as a module.

So what about that ``-m`` option? Having to cd into the python module directory
every time you need to execute a module as a script is cumbersome. The ``-m``
flag is basically a shortcut. These are basically the same::

    cd /usr/local/lib/python3.3
    python3.3 random.py

Same as::

    python3.3 -m random     #<-- I can do this from any directory.


The modules in the standard library have no obligation to do anything useful,
or even anything at all, if execute directly but you can use the same idea to
execute modules as scripts from packages you create.

-Modulok-



More information about the Python-list mailing list