When writing Python scripts, we often need to pass command line arguments to our program. The sys.argv
attribute in Python provides a simple way to access these command line arguments.
What is sys.argv
?
In Python, the sys.argv
variable is a list that contains the command line arguments passed to the script. The first element (sys.argv[0]
) is the name of the script itself, and the subsequent elements (sys.argv[1]
onwards) are the arguments passed by the user.
How to use sys.argv
To access the command line arguments using sys.argv
, we follow these steps:
- Import the
sys
module:import sys
- Access the command line arguments using
sys.argv
:argument1 = sys.argv[1] argument2 = sys.argv[2]
Example
Let’s consider a simple example to illustrate the usage of sys.argv
. Assume we have a Python script called my_script.py
, which takes two arguments: a file name and a delimiter. We want to print these arguments to the console.
Here is the code for my_script.py
:
import sys
filename = sys.argv[1]
delimiter = sys.argv[2]
print("File name:", filename)
print("Delimiter:", delimiter)
To execute this script with command line arguments, we run the following command:
python my_script.py data.txt ","
The output would be:
File name: data.txt
Delimiter: ,
Conclusion
The sys.argv
attribute in Python provides a convenient way to access command line arguments passed to a script. By using this attribute, we can enhance the functionality of our scripts and make them more versatile.