Scripting >> Python >> Examples >> Arguments >> How to count and use command line arguments passed to the script

Example 1

arguments.py

import sys
NumArgs = len(sys.argv)
ScriptName = sys.argv[0]

if NumArgs < 3 :
   # incorrect number of arguments passed, show script syntax
   print( "\nSyntax: {} Arg1 Arg2\n".format(ScriptName) )
else:
   # correct number of arguments were passed, proceed
   arg1 = sys.argv[1]
   arg2 = sys.argv[2]
   print( "Processing {} with arguments {} {}\n".format(ScriptName,arg1,arg2) )
 

Sample run

# ./arguments.py

Syntax: ./arguments.py Arg1 Arg2


# ./arguments.py first

Syntax: ./arguments.py Arg1 Arg2


# ./arguments.py first second
Processing ./arguments.py with arguments first second