In Python user-defined input variables can be passed to the scripts. These variables are helpful in making the code more robust, reusable. Python provides different ways to pass the command line arguments.
In this post I am going to cover methods, one is directly passing the variable values and the other one is using the key to pass the variable value
Method1: use sys.argv
Sys.argv method can be used to pass the input variables to the python script directly. Python will read the variables in the order they are passed to the script. create a file test.py with to read the inputs using sys.argv method
Import sys
variableList = sys.argv
print(variableList, end = ” “)
#Run Python script
python test.py 1 2 3 4 5
# Output
[‘test.py’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’]
test1.py have printed the input variables passed to the script along with the python script name. whenever sys.argv method is used, the first argument will always be the python script name. Create another script test1.py, which will read all the arguments from the index value to the last.
import sys
variableList = sys.argv
for i in range(1, sys.argv):
print(i, end = ” “)
# Run python snippet
python test_1.py 1 2 3 4 5
# Output
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]
Method2: Using argparser
Another method is to use the argparser. Argparser helps in passing the defined number of arguments to the script. While developing the snippet, the developer needs to define the variable key name and the same to be passed to read the arguments. This approach is helpful if the user wants to create some optional input variables.
Variables can be passed using –<variable_key> or -<variable_key_char>.
Consider below sample code
#Import the argparser library and passing command-line arguments
parser = argparse.ArgumentParser(description = ‘Pass the command line variables’)
parser.add_argument(‘-c’, ‘–country’, help = ‘Country Name’, required = True)
parser.add_argument(‘-i’, ‘–id’, help = ‘Id number’)
args = parser.parse_args()
# Assigning the command line input to the variables
country = args.country
id = args.id
print(country)
print(id)
#Run the python script
PS D:\Hadoop Tech> python .\commandLineArgs.py -c India
India
PS D:\Hadoop Tech> python .\commandLineArgs.py -c India -i 1
India
1
PS D:\Hadoop Tech> python .\commandLineArgs.py -i 1
usage: commandLineArgs.py [-h] -c COUNTRY [-i ID]
commandLineArgs.py: error: the following arguments are required: -c/–country
PS D:\Hadoop Tech>
Argparser allowed passing the command line input as required and optional. It is helpful to create the code redundantly. Also, it is helpful to the user to understand which variables they need to pass. Using the argparser, order of passing the variables is not important, just need to pass the variable value with the key.
Kindly share your feedback and questions and subscribe Hadoop Tech and our facebook page(Hadoop Tech) for more articles. Follow on GitHub
