Product SiteDocumentation Site


In this example we will copy a given file to another file.

#!/usr/bin/env python
import sys
if len(sys.argv) < 3:
    print "Wrong parameter"
    print "./ file1 file2"
f1 = open(sys.argv[1])
s =
f2 = open(sys.argv[2], 'w')

You can see we used a new module here sys. sys.argv contains all command line parameters. Remember cp command in shell, after cp we type first the file to be copied and then the new file name.
The first value in sys.argv is the name of the command itself.

#!/usr/bin/env python
import sys
print "First value", sys.argv[0]
print "All values"
for i, x  in enumerate(sys.argv):
    print i, x

The output

[kd@kdlappy book]$ ./ Hi there
First value ./
All values
0 ./
1 Hi
2 there

Here we used a new function enumerate(iterableobject), which returns the index number and the value from the iterable object.