sys.argv Python
Introduction
This article is about arguments that are passed to a script from outside. For example, from the terminal.
Passing arguments to a script is a common practice for CI/CD.
Read about ordinary arguments, that is, those passed to a function inside a module, in the article
*args, **kwargs
To pass arguments to a Python script from the command line you need to use the library sys
import sys
Then each argument has to be received with sys.argv
a = sys.argv[0] b = sys.argv[1] c = sys.argv[2] …
sys.argv[0]
The zero element is the name of the script itself.
# zero.py import sys print(f"First argument argv[0] is {sys.argv[0]}")
python zero.py
You can pass some other arguments too, there will be no error.
python zero.py argument
First argument argv[0] is .\zero.py
On Linux
python3 zero.py
First argument argv[0] is zero.py
sys.argv[1]
The first element is the first argument passed.
# one.py import sys print(f"Second argument argv[1] is {sys.argv[1]}")
Such a script cannot be called without arguments.
python .\one.py
Traceback (most recent call last): File "C:\python\one.py", line 4, in <module> print(f"Second argument argv[1] is {sys.argv[1]}") ~~~~~~~~^^^ IndexError: list index out of range
python .\one.py Test
Second argument argv[1] is Test
Read about how to make a script robust against a missing argument in the next chapter.
An optional argument
If you need to keep the ability not to pass any arguments, you can add a length check on sys.argv
# one.py import sys if len(sys.argv) > 1: a = sys.argv[1] else: a = None print(f"Second argument argv[1] is {a}")
python .\one.py
Second argument argv[1] is None
python .\one.py Test
Second argument argv[1] is Test
You can set a strict condition on the number of arguments:
import sys if len(sys.argv) == 2: a = sys.argv[1] else: a = "default" print("a =", a) print(type(a))
python sysargs.py 2
a = 2 <class 'str'>
python sysargs.py
a = default <class 'str'>
An unknown number of arguments in advance
What to do if the number of arguments is not known in advance.
We use the following property
of lists
in Python
lst = ["a", "b", "c"] print(lst[1:])
['b', 'c']
import sys print(f"Script received positional args: {sys.argv[1:]}")
python positional.py arg1 arg2 'arg as phrase'
Script received positional args: ['arg1', 'arg2', 'arg as phrase']
Note the possibility of passing arguments with spaces using quotes.
Example
The script
add.py,
which adds two strings together.
Without a check for the existence of the argument.
# one.py import sys first = sys.argv[1] second = sys.argv[2] print(f"{first} + {second} = {first + second}")
python add.py topbicycle .ru
topbicycle + .ru = topbicycle.ru
Exactly two arguments can be passed to such a script.
Let us consider a similar script that successfully accepts a different number of arguments.
import sys st = "" for el in sys.argv[1:]: st += el print(st)
A different number of arguments can be passed to this script
python unknown_len.py
python unknown_len.py 1 2
12
python unknown_len.py 1 2 3 a b cde 4 5 None
123abcde45None
To do similar operations with integers, we use the function int() because even if numbers are passed, they will be received as strings.
import sys first = int(sys.argv[1]) second = int(sys.argv[2]) print(f"{first} + {second} = {first + second}")
python add.py 3 4
3 + 4 = 7
Now the same but for an unknown number of elements in advance. Some elements may not be convertible to the type int.
For variety we use range(1, len(sys.argv)) instead of sys.argv[1:]
import sys s = 0 x = 0 for i in range(1, len(sys.argv)): try: x = int(sys.argv[i]) except ValueError: x = 0 finally: s += x print(s)
python unknown_len.py 1 2 3 4 5
15
Non-numeric arguments can also be passed to the script
python unknown_len.py 1 2 3 a b cde 4 5 None
15
You can pass nothing, there will be no error. The sum will be zero.
python unknown_len.py
0
Example 2
Consider the script words.py from the course by Pluralsight
import sys from urllib.request import urlopen def fetch_words(url): # story = urlopen("https://testsetup.site/testdata/words_en.txt") story = urlopen(url) story_words = [] for line in story: line_words = line.decode("utf8").split() for word in line_words: story_words.append(word) story.close() return story_words def print_words(story_words): for word in story_words: print(word) def main(): url = sys.argv[1] words = fetch_words(url) print_words(words) if __name__ == "__main__": main()
This script will not work unless the required url is passed through the terminal
python words.py "https://testsetup.site/testdata/words_en.txt"
It is also desirable to provide for calling main() after import.
In its current form there will be problems
python
Python 3.9.5 (default, Jun 15 2021, 15:30:04) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information.
>>> from words import *
>>> main()
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/andrei/python/words.py", line 23, in main url = sys.argv[1] IndexError: list index out of range
>>> main("https://testsetup.site/testdata/words_en.txt")
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: main() takes 0 positional arguments but 1 was given
The problem is solved by adding sys.argv[1] to the main call
def main(url): words = fetch_words(url) print_words(words) if __name__ == "__main__": main(sys.argv[1])
>>> main("https://testsetup.site/testdata/words_en.txt")
In other languages
In
C
the analogous function is performed by
int argc, char* argv[]
In
Bash
it is
built in by default
.
Article author: Andrei Olegovich