9) c. Command Line Arguments

You can go a step further to make your application more flexible in how it is launched by using command line arguments.

Here is the simplest and the most low-level example.

1
2
3
4
5
# my_script.py

import sys

print(sys.argv)



Now, we run this python file from the terminal window in the usual way. However, this time we also add a couple of strings after the file name.

These strings are called “command line parameters“. This is because they’re “parameter” values, or values that will get consumed as variables inside the code. And they’re passed during the call from command-line (terminal).

1
python my_script.py "Hello world!" "Something else" -my_flag=1
1
2
Output:
['my_script.py', 'Hello world!', 'Something else', '-my_flag=1']



As you can see you can use the argv property from the sys module to list all of the arguments passed to the Python interpreter. The first element will always be the name of the script that you are executing and the remaining elements, if any, will be the arguments you passed to your script.



You can treat argv like a list and access specific arguments by using indices.

1
2
3
4
5
6
7
8
9
# greetings.py

import sys

if len(sys.argv) > 1:
    # Remember that the first element is always the name of the script.
    print("Hello, " + ", ".join(sys.argv[1:]) + "!")
else:
    print("Hello, everyone!")



Here is what we’re doing. You’ve written your python code in a file named script1.py. While executing it in the terminal you pass the command line arguments:



Now call this file from the terminal/command line:

1
python greetings.py "John" "Mary" "William"
1
2
Output:
Hello, John, Mary, William!



However, using sys.argv does not scale very well if your application has multiple modules. It is best used when you’re creating a standalone tool and you absolutely must pass command line arguments.