Argument Parsing with argparse in Python

NeuralNine · Intermediate ·⚡ Algorithms & Data Structures ·2y ago

Key Takeaways

The video demonstrates how to use the argparse library in Python to parse command line arguments, including adding positional and optional arguments, using help options, and specifying data types for arguments. It also covers advanced topics such as using argparse with numbers and floats, limiting choices, and adding extra options with verbosity and file arguments.

Full Transcript

what is going on guys welcome back in this video today we're going to learn how to build professional CLI applications and parse arguments using the arc parse package in Python so let us get right into [Music] it all right so we're going to talk about the arc pars package in this video today which is a core python package that allows us to easily parse command line Arguments for our applications in Python and what this basically looks like is the same it looks like for almost all command line applications if you use something like grab for example you can provide certain options parameters uh arguments and you can also use the help option to see how to properly use this tool so you have all the different options here and this is true for almost every command line tool so curl for example I can also get the information here how to use it what the arguments are and what the different options are so this is what we're going to do in Python today how can we add our own options and arguments to our command line applications in an easy way so for this we're going to open up a new python file and we're going to call it Adder py because we're going to build a simple Adder now you can call this whatever you want but the idea of this tool is it's going to be able to add numbers and in addition to that we're going to have different options on how to display the result and what to do with the result just so we can go through the example here so we're going to start by importing The Arc parse package which as I mentioned is a core python package so we don't need to install it and what we're going to do first is we're going to define a parser instance so parser equals argument parser or actually Arc par argument parser and to this parser now we can add certain arguments and we have different types of arguments that we can add so we can say parser add argument and now we can add a positional argument so something that has to be provided after the name of the tool so in this case add rpy and then some value that is not specified with a flag or we can specify different flags so to give you a simple example of this we're going to call this first argument greeting this is going to be how this tool greets us as a user and what we're going to specify here is just the word greeting and then we're going to say help equals and the description of what this does basically so uh the greeting message displayed something like this now if we keep it like that if that is basically our whole tool what we can do now is we can say arguments equals parser dop parse arguments and we can just print the arguments as a whole or we can print specifically one key which in our case would be greeting and now if I open up the command line to navigate to this direction to this directory here I can say Python 3 uh adder and it will tell me usage Adder py greeting error the following arguments are required greeting because I didn't provide anything if I say hello for example it's going to print the greeting and this is the dictionary basically the namespace greeting equals hello um and I can also use the help option so I can say Dash to see how to use this this is automatically generated I don't have to provide this myself so you can see already this is quite convenient I can Define arguments and then I can parse the arguments and I can get them here as a dictionary sort of now this is a positional argument what I can also do is I can specify Flags so options essentially and how I do this is I basically say Dash and then a character for example let's say n and then let me just remove all of this here then we provide a second version which is the Double Dash um version where I have the full word which is numbers in my case um and then we can specify different things so for example for example I can specify a data type I can say that the numbers that I want to provide here are floats uh so by default we get strings if I provide float I get actual numbers from the command line um and then what we can also do is we can say uh that I want to have multiple arguments so I can say the number of arguments that I want to accept here are two so I want to have two numbers not just one value so I would say dashn and then I would provide two values not just one value and then of course we have a help text again the numbers to be added for example this is quite simple what I can do now first of all is I can print of course the numbers if provided uh and I can also I can say if arguments. numbers is not none I can print the result of the addition so arcs numbers this is then of course a list numbers one uh then I can go ahead and I can just uh run this again with hello if I don't provide anything you can just see I have none here because the numbers are not provided if I now go ahead and say DN and I just provide one number it will tell me expected two arguments if I provide a second number it's going to give me the result of the addition and you can see this is now what the uh numbers object looks like so 30 is the result of 10 + 20 of course um yeah so that is basically the idea of having these options here now we can also go ahead and specify an unlimited amount of numbers so I can say that I want to have a star here in asterisk and this basically means I can have as many sorry as many numbers as I want so I can say print sum and then r numbers and then I could provide more numbers as you can see so this also works now what we can also do is we can limit the choices so for example I might want to add an argument called verbosity so how much I want to display Dash uh V and D- verbose or verbosity and then I can say that this is a type integer and I want to have certain choices the choices are basically a limited list 012 and um yeah I can then provide also help text determines how much info is displayed or something like this and then basically I can just go ahead and say um I can I can basically make a distinction if ARX do verbosity is none then I can basically say just print the result of the so I can basically just do this just print the result of the calculation and maybe also print uh the greeting so that's the minimum thing then maybe I can do also uh else and then I can say if the value is zero I can do this same thing probably there's a more intelligent way to structure this uh and then I can say basically okay if I also have the verocity being equal to uh or actually maybe we should say greater than or equal to and then I can say okay if it's not zero or if it's also greater than or equal to one then I can print some extra stuff I don't know maybe the arcs numbers you can you can decide what you want you want to do here and then you can say if it's two in addition to all this stuff above velocity I can print some extra information so extra info or something like this so this would then add um this extra option so I can say here again let me just zoom in a little bit I can say Python 3 uh on Python 3 adder Y and then I can say hello I can say- N1 2030 then I can say- V zero then I would get this - V1 I would get more- V2 I would get even more than that and then if I say three it will tell me that this is an invalid choice this is not something that I can do um now I can also add now other arguments so for example uh I'm not going to go through this whole thing now because it doesn't really matter but I could also add a um f flag here or a-- file flag which basically is of type uh string and then instead of putting this out instead of always printing this I could save this in an output string and then I could write it to a file so I can say if uh file is not none then use the file type or the file name here as the path and then write it to a file instead of printing it uh but one last thing that I want to show you here is you can also have Bo flag so you can have flags that you don't need to specify any additional Arguments for so in this case we say dashn and we provide numbers here we say- V and we provide also numbers I can also say parser at argument and then I can say maybe something like debu D- debu and I can say the action here is store true store true and then we can describe this as enables ebook mode and then now basically it is either going to be true or false it will not be none if it's not specified it's going to be false if it's specified it's going to be true and then basically we can use this to decide uh what to do so one thing that I could do is I can say import time I'm just making something up right now and I can say here if Arc debug I can say start equals Time pro counter then I can do this in the end as well with end and I can print end minus start only if debug is enabled so I can basically run the same thing here you can see and then I can basically say-- debug and you would get the time measurement so yeah this is how you can use the core python package Arc pars to easily and professionally parse command line Arguments for your application so that's it for today's video I hope you enjoyed it and hope you learned something if so let me know by hit h a like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this Channel and hit the notification Bell to not miss a single future video for free other than that thank you much for watching see you in the next video and bye

Original Description

In this video today, we learn how to do argument parsing for command line applications in Python. ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 📚 Programming Books & Merch 📚 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/ 👕 Programming Merch: https://www.neuralnine.com/shop 💼 Services 💼 💻 Freelancing & Tutoring: https://www.neuralnine.com/services 🌐 Social Media & Contact 🌐 📱 Website: https://www.neuralnine.com/ 📷 Instagram: https://www.instagram.com/neuralnine 🐦 Twitter: https://twitter.com/neuralnine 🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/ 📁 GitHub: https://github.com/NeuralNine 🎙 Discord: https://discord.gg/JU4xr8U3dm
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeuralNine · NeuralNine · 0 of 60

← Previous Next →
1 Visualizing Stock Data With Candlestick Charts in Python
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
2 Python Beginner Tutorial #1 - Installation and First Program
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
3 Python Beginner Tutorial #2 - Variables and Data Types
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
4 Python Beginner Tutorial #3 - Operators and User Input
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
5 Python Beginner Tutorial #4 - If Statements and Conditions
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
6 Python Beginner Tutorial #5 - Loops
Python Beginner Tutorial #5 - Loops
NeuralNine
7 Python Beginner Tutorial #6 - Sequences and Collections
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
8 Python Beginner Tutorial #7 - Functions
Python Beginner Tutorial #7 - Functions
NeuralNine
9 Python Beginner Tutorial #8 - Exception Handling
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
10 Python Beginner Tutorial #9 - File Operations
Python Beginner Tutorial #9 - File Operations
NeuralNine
11 Python Beginner Tutorial #10 - String Functions
Python Beginner Tutorial #10 - String Functions
NeuralNine
12 Python Intermediate Tutorial #1 - Classes and Objects
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
13 Python Intermediate Tutorial #2 - Inheritance
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
14 Python Intermediate Tutorial #3 - Multithreading
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
15 Python Intermediate Tutorial #4 - Synchronizing Threads
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
16 Python Intermediate Tutorial #5 - Events and Daemon Threads
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
17 Python Intermediate Tutorial #6 - Queues
Python Intermediate Tutorial #6 - Queues
NeuralNine
18 Python Intermediate Tutorial #7 - Sockets and Network Programming
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
19 Python Intermediate Tutorial #8 - Database Programming
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
20 Python Intermediate Tutorial #9 - Recursion
Python Intermediate Tutorial #9 - Recursion
NeuralNine
21 Python Intermediate Tutorial #10 - XML Processing
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
22 Python Intermediate Tutorial #11 - Logging
Python Intermediate Tutorial #11 - Logging
NeuralNine
23 Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
24 Python Data Science Tutorial #2 - NumPy Arrays
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
25 Python Data Science Tutorial #3 - Numpy Functions
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
26 Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
27 Python Data Science Tutorial #5 - Subplots and Multiple Windows
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
28 Python Data Science Tutorial #6 - Matplotlib Styling
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
29 Python Data Science Tutorial #7 - Bar Charts with Matplotlib
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
30 Python Data Science Tutorial #8 - Pie Charts with Matplotlib
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
31 Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
32 Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
33 Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
34 Python Data Science Tutorial #12 - Pandas Series
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
35 Python Data Science Tutorial #13 - Pandas Data Frames
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
36 Python Data Science Tutorial #14 - Pandas Statistics
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
37 Python Data Science Tutorial #15 - Pandas Sorting and Functions
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
38 Python Data Science Tutorial #16 - Pandas Merging Data Frames
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
39 Python Data Science Tutorial #17 - Pandas Queries
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
40 Python Machine Learning Tutorial #1 - What is Machine Learning?
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
41 Python Machine Learning Tutorial #2 - Linear Regression
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
42 Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
43 Python Machine Learning #4 - Support Vector Machines
Python Machine Learning #4 - Support Vector Machines
NeuralNine
44 Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
45 Python Machine Learning Tutorial #6 - K-Means Clustering
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
46 Python Machine Learning Tutorial #7 - Neural Networks
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
47 Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
48 Generating Poetic Texts with Recurrent Neural Networks in Python
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
49 Stock Portfolio Visualization with Matplotlib in Python
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
50 Analyzing Coronavirus with Python (COVID-19)
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
51 Making Text Images Readable Again with Python and OpenCV
Making Text Images Readable Again with Python and OpenCV
NeuralNine
52 Neural Networks Simply Explained (Theory)
Neural Networks Simply Explained (Theory)
NeuralNine
53 Motion Filtering with OpenCV in Python
Motion Filtering with OpenCV in Python
NeuralNine
54 Top 5 Programming Languages To Learn in 2020
Top 5 Programming Languages To Learn in 2020
NeuralNine
55 Simple TCP Chat Room in Python
Simple TCP Chat Room in Python
NeuralNine
56 Image Classification with Neural Networks in Python
Image Classification with Neural Networks in Python
NeuralNine
57 Edge Detection with OpenCV in Python
Edge Detection with OpenCV in Python
NeuralNine
58 S&P 500 Web Scraping with Python
S&P 500 Web Scraping with Python
NeuralNine
59 Simple Sentiment Text Analysis in Python
Simple Sentiment Text Analysis in Python
NeuralNine
60 Introduction - Algorithms & Data Structures #1
Introduction - Algorithms & Data Structures #1
NeuralNine

This video teaches how to use argparse to parse command line arguments in Python, including adding positional and optional arguments, using help options, and specifying data types for arguments. It also covers advanced topics such as using argparse with numbers and floats, limiting choices, and adding extra options with verbosity and file arguments. By the end of this video, you will be able to write command line applications with argument parsing and implement debugging and performance measurem

Key Takeaways
  1. Import the argparse package
  2. Define a parser instance
  3. Add positional and optional arguments to the parser
  4. Use the help option to display usage and available arguments
  5. Parse the command line arguments using the parser object
  6. Print numbers if provided
  7. Add numbers if provided
  8. Provide help text
  9. Limit choices with choices argument
  10. Add extra options with verbosity and file arguments
💡 The argparse library provides a powerful way to parse command line arguments in Python, allowing you to create flexible and user-friendly CLI applications.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →