Command line arguments in Python
This tutorial is Command line arguments in Python. Python is a popular programming language, as well as having support for most operating systems. Python users use specific commands, set options, and more. these options could tell the tool to output additional information, like read data from a specified source, or send output to a certain location.
CLI(Command Line Input) tools arguments are passed differently, depending on your operating system:
Unix-like: – followed by a letter, like -h , or — followed by a word, like –help
Windows: / followed by either a letter, or word, like /help.
handle Command line arguments with Python
Python 3 supports a number of different ways to handle command-line arguments. The Python built-in way is to use the sys module.
sys Module
The sys module implements (System-specific parameters and functions) the command line arguments in a simple list structure named sys.argv.
Example
# first-arguments.py import sys print ("The First argument is {}".format(sys.argv[0]))
Save this code in a named first-arguments.py.
Run
$ python3 first-arguments.py
The First argument is first-arguments.py
Count the Number of Arguments
We count the number of command-line arguments using the built-in len() method. The actual number of arguments passed by the user is len(sys.argv) – 1.
Example
# arguments-count.py import sys # Count the arguments arguments = len(sys.argv) - 1 print ("Count argument {}".format(arguments))
Save this code in a named arguments-count.py.
Run
$ python3 arguments-count.py
Count argument 0
$ python3 arguments-count.py --help me
Count argument 2
$ python arguments-count.py --option "long string"
Count argument 2