Table of Contents
What is Python sys.argv?
Sys.argv() is an array for command line arguments in Python, consisting of all strings (which represent system commands) passed to your python script or program, except for the first item, which always means the invoking script or filename.
Command-line arguments are those values passed during the calling of the program and the calling statement. Thus, the first element of the array sys.argv() is the name of the program itself.
What is the sys module?
Sys module is used for manipulation in Python runtime environment. It provides access to different variables and functions for interaction with the interpreter.
If you’re working with Python sys.argv , import the sys module first by typing “import sys” before making any other statements or functions within your script that need access to this module.
import sys print("Name of Program: ", sys.argv)
What Functions are used with Python sys.argv?
It counts the number of arguments passed on the command line, which will help you create sequences of instructions accordingly. It also counts the program name as an argument because the iteration starts at 0 by default. You can change it with other commands.
It converts the array to a string array to make the command line array look better.
import sys print ("What is the name of the script? ", sys.argv) print ("How many arguments?", len(sys.argv)) print ("What are the arguments? " , str(sys.argv))
If you don’t want to include the program name in the list of arguments, you can use ( len(sys.argv)-1)
import sys print("Number of arguments with program name:", len(sys.argv)) print("Number of elements without program name:", (len(sys.argv)-1))
This article discussed how to use the Python sys.argv() in command line arguments. If you are going to work with these types of values, it might be worth taking some time now to learn about how this data structure works so that you don’t get confused later down the road. I hope this tutorial helped you in understanding sys.argv in Python.