Archive - Originally posted on "The Horse's Mouth" - 2015-02-23 17:54:48 - Graham Ellis
The sys module in Python gives you access to operating system parameters such as the command line interface, via an ordered collection (I think a list, may be a tuple) called argv. Although many / most users these days don't use the command line directly, it's often used internally between programs in a batch file or command / shell script, in regular time jobs, between web servers and programs, and so on - so you may need to use it more than you expect.
For this week's course I've written a very shorr example [here] to show this in use.
from sys import *
for thing in argv:
print "I gotta", thing
Note that the first value that comes back is the name of your program, and the following items are individual paramaters as processed by the command line handler. Thus ...
Just the command - a single parameter:
trainee@kingston:~/elen$ avx
I gotta ./avx
The command with some space separated parameters (note that "-l" looks like an option but is really just a parameter):
trainee@kingston:~/elen$ avx -l 15.0 metres
I gotta ./avx
I gotta -l
I gotta 15.0
I gotta metres
Use of command line special characters will be reflected in what your python program gets - here using quotes to make a single string for you:
trainee@kingston:~/elen$ avx "Single String"
I gotta ./avx
I gotta Single String
... and here piping what you output from your program into another command; you don't see this is happening from argv:
trainee@kingston:~/elen$ avx "Single String" | cat
I gotta ./avx
I gotta Single String