Sys.argv is a useful feature in Python that allows you to pass command line arguments to a Python script. It provides a simple way to accept user input when running scripts from the terminal.
In this comprehensive guide, we‘ll cover everything you need to know about using sys.argv in Python, including:
- What is sys.argv?
- Accessing command line arguments with sys.argv
- sys.argv[0] and the script name
- Handling multiple command line arguments
- Converting sys.argv values to other data types
- Common errors and troubleshooting with sys.argv
- When to use sys.argv vs argparse
So if you want to learn how to better utilize command line arguments in your Python scripts, keep reading!
What is Sys.argv?
Sys.argv is a variable that contains a list of all command line arguments passed to a Python script. It is part of the sys module and does not need to be imported separately.
Here is the key information you need to know about sys.argv:
- It is a list variable that contains string elements
- The first element, sys.argv[0], is always the name of the script itself
- Any additional elements contain the command line arguments provided by the user
For example, say we have a Python script called myscript.py. When running this script from the terminal, we pass additional command line arguments like:
python myscript.py firstarg secondarg thirdarg
Inside myscript.py, the sys.argv variable would now contain:
[‘myscript.py‘, ‘firstarg‘, ‘secondarg‘, ‘thirdarg‘]
The sys.argv list contains all 4 arguments provided from the terminal when running the script.
This allows your Python scripts to flexibly accept input in a simple way when executed from the command line.
Accessing Command Line Arguments with Sys.argv
The main purpose of sys.argv is to enable a Python programmer to access command line arguments.
The sys.argv list contains all arguments passed in, starting with the name of the script as sys.argv[0]. Any additional elements in the list are the arguments provided by the user.
Here is a simple example script called args.py that prints out the sys.argv list:
import sys
print(sys.argv)
Now when running this script with some command line arguments:
python args.py first second third
It prints out:
[‘args.py‘, ‘first‘, ‘second‘, ‘third‘]
We can see the script name was automatically added, plus the 3 arguments we provided from the terminal.
To actually access those arguments in our Python code, we just treat sys.argv as a normal list:
first_arg = sys.argv[1]
second_arg = sys.argv[2]
third_arg = sys.argv[3]
So sys.argv provides an easy way to access all command line arguments as string elements in a Python list.
Sys.argv[0] and the Script Name
It‘s important to understand that the first element of sys.argv, denoted sys.argv[0], will always contain the name of the script itself. This happens automatically.
So in args.py from the example above, sys.argv[0] contains the string ‘args.py‘.
Knowing this can prevent confusion when trying to access the "first" argument passed by the user. That is actually the 2nd element, sys.argv[1].
We can modify the script to print just the script name:
import sys
script_name = sys.argv[0]
print(f"Script name: {script_name}")
Now running it shows:
Script name: args.py
So when iterating through sys.argv, just remember index 0 is reserved for the script name. Any user-provided arguments start at sys.argv[1] and beyond.
Handling Multiple Command Line Arguments
A major advantage of sys.argv is it allows your Python scripts to flexibly accept any number of command line arguments.
For example, we can access 4 arguments passed like:
first = sys.argv[1]
second = sys.argv[2]
third = sys.argv[3]
fourth = sys.argv[4]
But hard coding indexes can get tricky if the number of arguments might vary each time the script runs.
Instead, we can loop through sys.argv and handle any number of arguments dynamically:
import sys
for arg in sys.argv[1:]:
print(arg)
By looping from index 1 and up, we are effectively ignoring sys.argv[0] which contains the script name. Then we can conveniently print all arguments actually passed by the user.
With this approach, whether 2 arguments or 10 arguments are provided, our script handles them all generically by iterating through sys.argv.
We can extend this technique to perform any kind of processing on the arguments:
import sys
usernames = []
for arg in sys.argv[1:]:
usernames.append(arg)
print(usernames)
Here we are collecting all arguments into a usernames list. This provides flexibility for the user to provide any number of usernames on the command line.
So leveraging sys.argv in a loop is generally recommended instead of hard coding indexes, since you don‘t always know how many command line arguments your user will pass to the script.
Converting Sys.argv Values to Other Data Types
One key aspect of sys.argv is that all elements are passed in as string values by default. So if you need to perform mathematical calculations or other processing, they will likely need to be converted to integers, floats, etc.
For example, this script tries to add the numbers passed as command line arguments:
import sys
first_num = sys.argv[1]
second_num = sys.argv[2]
sum = first_num + second_num
print(sum)
Running it results in a traceback error:
Traceback (most recent call last):
File "args.py", line 6, in <module>
sum = first_num + second_num
TypeError: unsupported operand type(s) for +: ‘str‘ and ‘str‘
This happens because the arguments are strings, and Python can‘t directly add strings numerically.
To fix it, we need to explicitly convert them to numbers first using int() or float():
first_num = int(sys.argv[1])
second_num = int(sys.argv[2])
Now when running the script, it properly turns the arguments into integers and can add them:
python args.py 5 10
15
The same would apply to floating point numbers using float() or other data types like dates.
So remember, if you need to perform any non-string processing on command line arguments, add int(), float() etc. to convert sys.argv elements as required in your script.
Common Errors and Troubleshooting
When first getting started with sys.argv, it‘s fairly common to run into errors. Here are some tips for troubleshooting issues you might encounter:
Index out of range errors – This means you are trying to access an index greater than the number of arguments provided. Double check that your script handles varying numbers of arguments, for example by looping instead of hard coding indexes.
Type conversion issues – Be sure to wrap sys.argv elements in int(), float() etc. as covered above so you can process the string values as different data types.
No arguments provided – You may get index errors or other issues if a script expects arguments, but none were provided when running it. Add checks for the length of sys.argv with len(sys.argv) or default behavior if it‘s lower than expected.
Here is an example script that handles some common sys.argv errors:
import sys
if len(sys.argv) < 3:
print("Please provide at least 2 command line arguments")
sys.exit(1)
try:
first = float(sys.argv[1])
second = float(sys.argv[2])
except ValueError:
print("Invalid input, could not convert to floats")
sys.exit(1)
sum = first + second
print(f"{first} + {second} = {sum}")
In this case we are requiring at least two numeric arguments. This handles issues converting to floats or not having enough arguments provided from the user.
Remember, users invoking your script may provide bad input or no input sometimes, so handling errors robustly is important!
When to Use Sys.argv vs. Argparse
Sys.argv provides a very convenient way to access command line arguments passed to Python scripts. However, for more advanced argument processing, you will likely want to check out the argparse module instead.
Some key differences between the two:
-
argparse allows creating user-friendly command line interfaces, with support for features like help messages, argument types, default values, etc.
-
sys.argv just gives you the arguments directly, requiring custom parsing and validation logic in your code
So in summary:
- Use sys.argv for simple scripts with a limited number of expected arguments
- Use argparse for larger scripts to properly define arguments, usage help and robust validation
Consider converting from sys.argv to argparse once you find yourself needing to add many flags, validate ranges, show usage instructions for end users, etc.
It will be less custom code compared to rolling your own parsing and validation routines for sys.argv.
Summary
Here‘s a quick recap on some of the key points about Python‘s sys.argv:
- sys.argv contains command line arguments as a list of string elements
- sys.argv[0] always contains the script name
- Converting args with int(), float(), etc may be required for processing
- Use sys.argv when handling a limited number of expected cmd line args
- Consider argparse for more complex argument validation and help generation
Hopefully this detailed overview gives you a better understanding how to leverage sys.argv in your own Python command line scripts!
It provides a simple yet flexible way to accept input from users when executing your scripts from the terminal.
To dig into code examples using sys.argv, be sure to check out the official Python documentation, tutorials like this, or just experiment with some small test scripts of your own.


