To get arguments from the command line, you have to use sys.argv list. It contains a list of arguments passed to the script via the command line.
To use command line arguments, you have to import the sys module.
Now, you can access the script name, number of arguments, and display the list of arguments.
Let’s run this code:
If you run this code without any arguments, the interpreter will return this response:
Here, you can see:
- Script name, which is main.py.
- A number of arguments. There is 1 because there only a script name counter as an argument.
- List. Only one item on the list, which is only the script name.
Run file from the command line
Now, open the command line. Move to the directory with the script and run the following line:
Now, the result is slightly different. We added an additional three arguments, so far, we have 4 in total. All of them are stored inside the list that is displayed in the next line.
If you want to display the list of arguments without a file name, you can add this line to your code.
This is the result: