Introduction to Python Programming/Python Programming - Command Line Arguments

From Wikibooks, open books for an open world
Jump to navigation Jump to search

8. Command Line Arguments[edit | edit source]

There is a module sys that needs to be imported to read the command line arguments from the Python interpreter.

Here’s an example.

   >>> import sys
   >>> print 'The number of arguments at command line are ', len(sys.argv)
   The number of arguments at command line are  1
   No.  0 Arugment  C:/Users/Desktop/Projects/Upwork/firstworkspace.py
   >>>C:\Users\Desktop\Projects\Upwork>python second.py
   The number of arguments at command line are  1
   And the arguments are Argument List: ['second.py']
   >>>C:\Users\ Desktop\Projects\Upwork>python second.py 1 2 3 4
   The number of arguments at command line are  5
   And the arguments are Argument List: ['second.py', '1', '2', '3', '4']
   >>> count=0
   for b in sys.argv:
       print 'No. ', count, 'Arugment ', b
       count+=1
   >>>C:\Users\Desktop\Projects\Upwork>python second.py 1 2 3 4
   The number of arguments at command line are  5
   No.  0 Arugment  second.py
   No.  0 Arugment  1
   No.  0 Arugment  2
   No.  0 Arugment  3
   No.  0 Arugment  4
   C:\Users\Desktop\Projects\Upwork>python second.py 1 2 3 4
   The number of arguments at command line are  5
   No.  0 Arugment  second.py
   No.  1 Arugment  1
   No.  2 Arugment  2
   No.  3 Arugment  3
   No.  4 Arugment  4
   C:\Users\Desktop\Projects\Upwork