Intro of argparse
The argparse
module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse
will figure out how to parse those out of sys.argv
(see the following part for the details of this).
You can’t keep using Jupyter notebook all the time. The scripts files and a whole projects needs to be created for our task. The argparse
is the communication tools which let developers to make changes to the script from the terminal and don’t need to go into the code and change the parameters.
example
1 | import argparse |
This is a program that takes a list of integers and produce either the sum or the max.
Assume the name of file is prog.py
, and execute the file:
1 | python prog.py 1 2 3 4 |
See the details from docs of argparse.
Else
sys.argv
During using the argparse
module, sys.argv
is important since you may need it in the main()
function.
Code is sometimes like this:
1 | import argparse |
sys.argv
is the list of commandline arguments passed to the Python program. It represents all the items that come along via the command line input.
For the content of argv
, the first argument is always the script name, and it is also counted in the number of arguments. So even if you don’t pass any argument into your script, the sys.argv
variable always contains at least one element and it’s the script name.
Example
Execute this python script, assume it is named test.py
.
1 | import sys |
1 | python test.py |
The output should be:
1 | This is the name of the script: sysargv.py |
Reference
- python docs: argparse
- How to use sys.argv in Python ](https://www.pythonforbeginners.com/system/python-sys-argv)
- https://appdividend.com/2019/01/22/python-sys-argv-tutorial-command-line-arguments-example/