Hi, I'm Harlin and welcome to my blog. I write about Python, Alfresco and other cheesy comestibles.

Python - Using the -m Option to Run Modules

Do you ever make use of the Python interpreter's many options? These are often overlooked but if you ever take the time to see what's available, I think you'll be pleasantly surprised.

If you call python from the command line using --help, you'll see a number of other interesting options:

$ python --help
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
-B     : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d     : debug output from parser; also PYTHONDEBUG=x
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)
-h     : print this help message and exit (also --help)
-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I     : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O     : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x

... and there's a lot more ...

Personally, I like the -m option. The "m" stands for modules as in running modules in Python's path as scripts themselves.

One cool thing you can do is to quickly open a functional http server for a particular directory. This comes in handy if you have something in the directory that you would like to share with someone on your network.

Here's how you can do it:

# For Python 3.x:

$ python -m http.server

or if you're using Python 2.x:

$ python -m SimpleHTTPServer 8000

Another cool module is the "timeit" module. So cool in fact, I wrote another article on that subject here. You can use it to run inside your scripts if needed but it can also be run using the -m option.

For example, will it be faster to iterate through a range of 1000 numbers and do nothing or do some multiplication:

$ python -m timeit -c "[n * n for n in range(1000)]"
10000 loops, best of 3: 65.5 usec per loop

$ python -m timeit -c "[n * n for n in range(1000)]"
10000 loops, best of 3: 66.1 usec per loop

Were you aware you can also write your own simple tests for functions by putting the tests into the function's documentation?

The doctest module can help with that.

Here, you can use the doctest module and -m option to test your function:

#!/usr/bin/env python


def my_func(a, b=2):
    """
    >>> my_func(5)
    10
    >>> my_func(5, 3)
    15
    >>> my_func('Hello')
    'HelloHello'
    """
    return a * b

Note that in the comments for the function there are tests with a few different sets of parameters. And yep, you guessed it, we can use -m doctest here to run a test.

In this instance, call python -m like so (note that the -v gives you more output):

$ python -m doctest -v demo1.py 
Trying:
    my_func(5)
Expecting:
    10
ok
Trying:
    my_func(5, 3)
Expecting:
    15
ok
Trying:
    my_func('Hello')
Expecting:
    'HelloHello'
ok
1 items had no tests:
    demo1
1 items passed all tests:
   3 tests in demo1.my_func
3 tests in 2 items.
3 passed and 0 failed.
Test passed.

Another cool usage is using the markdown module. The markdown package can be used to convert markdown to html. I am including a sample markdown file called, appropriately enough, "sample_markdown.txt". The file's contents are as follows:

# Welcome To Sample Markdown!

## This is a smaller header

This is a paragraph. Typically, when you can't think of anything to write but you need to test out some formatting, it's a good idea to use some "lorem ipsum":

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc pharetra dapibus semper. Aenean eget velit tristique, tincidunt arcu sed, malesuada nibh. Maecenas sed gravida ipsum. Morbi diam turpis, porttitor quis quam ut, fermentum ullamcorper augue. 

Duis feugiat enim a nibh porttitor consequat. Nulla at purus eget ante scelerisque tempus id id massa. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. *Praesent* sollicitudin iaculis finibus. Phasellus quis pretium nulla. Sed lectus felis, vehicula vitae lectus a, hendrerit volutpat nibh. _Nulla eu ullamcorper mi, sit amet porta orci._ Cras dictum est aliquam turpis egestas blandit.

Here is a list of some ipsum words:

* Donec 
* congue
* quam 
* nec 

Ok, this is the end.

The markdown library does not come with Python out of the box but can be downloaded and installed in your Python environment:

$ pip install markdown

And then we can use the following command to generate some html from our markdown file:

$ python -m markdown sample_markdown.txt

<h1>Welcome To Sample Markdown!</h1>
<h2>This is a smaller header</h2>
<p>This is a paragraph. Typically, when you can't think of anything to write but you need to test out some formatting, it's a good idea to use some "lorem ipsum":</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc pharetra dapibus semper. Aenean eget velit tristique, tincidunt arcu sed, malesuada nibh. Maecenas sed gravida ipsum. Morbi diam turpis, porttitor quis quam ut, fermentum ullamcorper augue. </p>
<p>Duis feugiat enim a nibh porttitor consequat. Nulla at purus eget ante scelerisque tempus id id massa. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. <em>Praesent</em> sollicitudin iaculis finibus. Phasellus quis pretium nulla. Sed lectus felis, vehicula vitae lectus a, hendrerit volutpat nibh. <em>Nulla eu ullamcorper mi, sit amet porta orci.</em> Cras dictum est aliquam turpis egestas blandit.</p>
<p>Here is a list of some ipsum words:</p>
<ul>
<li>Donec </li>
<li>congue</li>
<li>quam </li>
<li>nec </li>
</ul>
<p>Ok, this is the end.</p>

If you wanted to, you can pipe it into an html file like so:

$ python -m markdown sample_markdown.txt > sample.html

I like using it to generate static html files. Pretty cool, isn't it?

I would challenge you to go around to many of the modules that come with Python out of the box and test them with the -m option. You will probably find a lot of unexpected and useful things.

Any Comments, Always Welcome!