Python Programming, news on the Voidspace Python Projects and all things techie.

python -me : a silly but useful command line trick

Python has a -c command line option that allows you to execute snippets of code and see the results.

One of the most common reasons I use this is to find the source code for a module in order to view it in a text editor:

$ mate `python -c "import module;print module.__file__[:-1]"`

Replace mate with gedit or your favourite text editor. The [:-1] is to chop off the trailing 'c' from '.pyc'.

In addition, I frequently attempt to use "-c" for simple calculations. I say attempt, because I usually forget that you need to use a print statement to actually see the results. My normal usage pattern goes something like this:

$ python -c "47/120.0" $ python -c "print 47/120.0" 0.391666666667

In a discussion about this on the python-ideas mailing list Georg Brandl suggested an alternative. If you compile python code (yes Python compiles code - to Python bytecode) with the 'single' flag then the results of evaluating expressions are echoed. This is how the interactive interpreter works:

>>> code = "1+1" >>> exec compile ( code , '<cmdline>' , 'single' ) 2

Another Python command line flag is -m <module>. This executes a module as a script and is very useful. Sooo... with a module called e.py on sys.path it will be executed as a script when invoked with python -me .

Foolishly following Georg's suggestion I've registered the e module on PyPI. You can now pip install e and then python -me . For example:

$ python -me 1+1 2

Like python -c but no need for a print statement.

It allows multiple expressions:

$ python -me 1+1 2+2 2 4

As a bonus, if the first argument is a module name then it will output the location of the module source code:

$ python -me os /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/os.py

This makes my "view the source in a text editor" trick:

$ mate `python -me module`

It's not bullet proof as it is a silly hack - so please don't look at the source code.

Nonetheless I think this is a hack I will actually use.

Archives