Command Line Arguments in Python Script


Python is used widely in linux, windows, and other platforms to provide useful utilities. In order to write utilities, such as the shell scripts in Linux, you might need to obtain the arguments from the shell’s prompt (e.g. ‘C:\’ in windows).

The very basic information of the arguments can be loaded by sys.argv. It is at least length of one, with the index[zero] being the path of the python script.

#!/usr/bin/env python
from sys import *

print "len(argv) = %d" % len(argv)
print "argv[0] = %s"  % argv[0]

for arg in argv:
        print arg

The sample output of the script if you give no arguments:

$ ./test.py
len(argv) = 1
argv[0] = ./test.py
./test.py

The sample output of the script if you give some arguments:

$ ./test.py 1 2 3 4
len(argv) = 5
argv[0] = ./test.py
./test.py
1
2
3
4

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
190 words
Last Post: Codeforces: B. Simple XML
Next Post: Include the Binary Files in Your Source Code

The Permanent URL is: Command Line Arguments in Python Script

Leave a Reply