Hello Pythonistas, welcome back.
You might know about the input function that is used to take input from the user in python. Here we will take a look at what is argv which is similar to the input function yet different.
Contents
What is argv?
The argv
is an argument variable which means it is a variable that works as an argument for our python file/script.
If you are using argv
in your program then you would need to run it in Command Prompt it will not work in IDLE or VS Code. (Don’t worry I will show you howđź‘Ť)
For using argv
we will first need to import it from an inbuilt(comes with python installation) library sys
. To import argv
of sys
in your program simply type:
from sys import argv
This means that we are getting argv
from the sys
library into our python file. Now that you got an idea of what is argv
let’s now see a few examples to make it more clear.
from sys import argv
script = argv
print("The script is called:", script)
To run it:-
- First, open it in the file location;
- Then, type cmd in the location bar and press enter;
- Next, type the file name in cmd and press enter; Your program will run like this👆;
NOTE:- You can run this much in VS Code or IDLE.
This program simply assigns the location of the file to the script
variable(Any variable name can be used instead of script
). Now let’s see how can you give more than one variable.
from sys import argv
script, first = argv
print("The script is called:", script)
print("Your first variable is:", first)
To run this:-
- The first two steps are the same as before;
- In the third step type, the file name, then a space, and then the value of the variable without any spaces. However, you can give a string with spaces. Just like I did above.
How is it different from user input?
Now, must have clearly got the difference between the input function and
argv
of sys.
The input function simply takes user input after you run the program.
And argv
is an argument variable that assigns values to variables before we run the program.
And a program containing the input function can run in any development environment whereas, a program having argv
might just run on the terminal.