To access command-line arguments in Python, you use the sys
module, specifically the sys.argv
list. Here’s a brief guide.
Import the sys
module: First, import the sys
module at the beginning of your script.Access sys.argv
: This list contains the command-line arguments passed to the script. The first element (sys.argv[0]
) is the name of the script, and the subsequent elements are the additional arguments.
Python how to access the command line argument.
The example program provided demonstrates how to access and utilize command-line arguments in Python, focusing on two methods: using the sys
module for basic argument retrieval and the argparse
module for advanced argument parsing.
Initially, the program employs the sys
module to access command-line arguments. By importing sys
and printing sys.argv
, the script shows the number of arguments passed and lists them. For instance, running python script.py arg1 arg2 arg3
would output the script name and the three arguments, indicating the flexibility and simplicity of sys.argv
for basic needs.
For more complex scenarios, the program uses the argparse module. argparse facilitates robust command-line argument parsing, enabling the definition of positional and optional arguments with detailed descriptions, default values, and type specifications. In the provided example, the argparse parser is configured to handle a list of integers and an optional –sum flag. The integers are added using parser.add_argument(‘integers’, …).
while –sum is defined with parser.add_argument(‘–sum’, …) to either sum the integers or find the maximum based on its presence.
while --sum
is defined with parser.add_argument('--sum', ...)
to either sum the integers or find the maximum based on its presence.
import sys # Print the number of arguments passed print(f"Number of arguments: {len(sys.argv)}") # Print the arguments themselves print(f"Arguments: {sys.argv}")
Output :5