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.
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).
python my_script.py "Hello world!" "Something else" -my_flag=1
['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.
if len(sys.argv) > 1:
# Remember that the first element is always the name of the script.
print("Hello, " + ", ".join(sys.argv[1:]) + "!")
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:
python greetings.py "John" "Mary" "William"
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.