Sunday, May 24, 2009

Command line tools take command line arguments

You all know them and use them; command line tools with arguments. Especially on linux, this is the way things go, but also in Windows. Think about the dos command dir, and its attributes;

  • dir /p: list directory one screen full at the time
  • dir /w: list directory in columns,
  • ....
On linux you have ls with a bunch of options, for example

ls -al

to show files with owners and permissions. How do we make tools that can take command line arguments in Python?

Fortunately, as the www.python.org site says, Python comes with batteries included. Command line arguments are stored in a list that can be accesed from the sys module. The stdin (command line input) arguments are found using sys.argv. If you use this line:

from sys import argv as inputargs

inputargs will be a list containing text strings with your input arguments. Then, if you have some script like this

from sys import argv as inputargs
myString = 'Hello '+inputargs[1]+', this is '+inputargs[2]+' speaking!'
print myString

The result of running this command:

./myscript.py guest "the owner"

will be:

Hello guest, this is the owner speaking!

Nice to know! We'll put it to use in the next post! Happy hacking :-)

No comments:

Post a Comment