Sunday, June 21, 2015

Lifehack - import directly from command line

If you're obsessed with UX as I am, and long repetitive commands seem to break your flow, you may appreciate this little trick for invoking Python from command line.

I invoke python from console/terminal to check some behavior that I tend to forget after a day in JavaScript or other programming languages. It is often way faster than reading the docs. It also helps to quickly try new PyPI libraries after installing with pip (saves on mouse clicking in IDE etc.).

Today I found a time saver that makes me happy. This example is typed for Windows, but there should be no problem for any Linux hacker to port it to their favorites. So instead of doing this:
> python [ENTER]
>>> import os [ENTER]
>>> os.name [ENTER]
'nt'
I can just type:
> import os [ENTER]
>>> os.name [ENTER]
'nt'
It should be now easy to understand how it works, so I will complicate it a bit. The trick is this little import.bat script, placed in system PATH:
@echo off
py -2 -c "import sys; print(sys.version)"
py -2 -i -c "import %*"
py here is a py.exe launcher that can call either Python 2 or Python 3 depending on argument. It comes installed with Windows Python versions. I like to know which Python I work with, so I've added version into to the command, and to avoid polluting the global space of new interpreter, the version is printed by separate command.