Command Line Arguments in Python

Another problem the beginner in Python faces 'to take input from the command line arguments' - maybe you want to give a text file name as a command line argument or you need it for another purpose (in the first time, my necessity was the earlier one).

The solution is to use sys.argv you need to import the sys module first. then sys.argv[0] contains the python filename itself, sys.argv[1] contains the next argument and so on...


import sys

print 'I am ', sys.argv[0]
print sys.argv[1]

Run the program: python my.py file.txt
Now you may assign the sys.argv[1] to a variable and do whatever you want.

To know more about sys module, Check http://docs.python.org/lib/module-sys.html

Hope you find this tip useful :)

Comments

zogness said…
So what if the filename is a text file full of say, hostnames or filenames that I want to iterate over?
Tamim Shahriar said…
I think first you need to read that file. Then you can iterate over. I am not sure though whether I got you right.
Amit Saha said…
@Zogness,

You may find this: http://docs.python.org/library/fileinput.html#module-fileinput useful.
Unknown said…
You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - Commando

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code