Input method to pass variable to Python Script

5221

We have already discussed input() function which is a builtin function in Python 3. In this article, we will explore another method which one can use to pass variable while executing the Python Script. 

This method is similar to passing arguments while executing a command in Linux. It can also be related to the C/C++ programming language main function arguments:

 int main(int argc, char *argv[]) { /* ... */ }

Let’s dive in to explore how to use it in Python. Do not worry, if you are not aware of the above function. Just look at the code given below and seek out the explanation given for the code.

Code: Input method to pass arguments to a Python script 

# Save the script as test.py
from sys import argv
script, first, second, third = argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)

 

Executing the script: 

> python test.py Learn Python Programming

Output: 

The script is called: test.py
Your first variable is: Learn
Your second variable is: Python
Your third variable is: Programming

Explanation:

The first line in the program from sys import argv refers to import the specific function from the sys package.  Instead of importing the complete sys package we imported specific module argv to keep the code minimum. You will learn it better when you will build your own modules, in the upcoming sections.

script, first, second, third = argv  This line unpack argv and get assigned to four variables script, first, second, and third. It refers to Assigning Multiple values to Multiple Variables in a single line

The rest of the code is simply printing the value stored in the variables.