No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python argparse Example with Code

by Khaleel O.
January 1, 2022
in Python
Reading Time: 4 mins read
A A
Python argparse Example
Python argparse Example

Now let’s do a Python argparse example with code. We will be using Python 3.8.10. Let’s go! ⚡⚡✨✨

In Python, the argparse module makes it possible to provide a command-line interface to the user. More specifically, a user can supply arguments/parameters at the command line to the python script at runtime, without having to include them manually as variables beforehand. We will demonstrate this shortly.

Before we begin, ensure that you have the argparse library installed. You can install it with the following command:

pip install argparse

Now that we’ve installed the required library, let’s write some code!

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--value', type=str, required=True)

args = parser.parse_args()

if (str(args.value[::-1])==str(args.value)):
    print(f'Reverse is {str(args.value[::-1])}. {args.value} IS a palindrome. ') 
else:
    print(f'Reverse is {str(args.value[::-1])}. {args.value} IS NOT A palindrome. ')

Let’s explain what is happening here:

  1. First we import the argparse library.
  2. The call argparse.ArgumentParser() creates a new ArgumentParser object. This object hold all the info necessary to parse the command line into Python data types. The name of our new object is parser.
  3. The method add_argument() defines how a single command line argument should be parsed. It accepts 13 possible parameters. In this case, we are supplying only 3 parameters: a name for the argument which is –value, a type for the argument of str which is the type that the argument will be converted to and the required flag which we set to True.
  4. The method parse_args() converts argument strings to objects. We don’t supply any arguments on this occasion but there are two possible arguments that can be supplied here: args and namespace. By default, both are set to None.
  5. We do a simple if-else statement to determine if the argument value supplied is a palindrome. Recall that a palindrome is a sequence of words, letters or numbers that reads the same backwards and forwards.

Ok great!🔥🔥 So now that we have written our code, we have to supply the arguments the correct way at the command line. Below is a screenshot of what must be typed at the command line to execute our code properly (Windows 10 OS was used in this example):

Python argparse Example
Python argparse Example

Let’s explain what is happening here:

  1. Ideally, you’d first open a new cmd window on Windows 10 or a new Terminal on Linux/Mac and type something very similar to the above command.
  2. The python executable name is usually python but this may differ depending on how you configured your system and python interpreter.
  3. The python script name is the name of the script file. On my system, the filename is PYTHON_ARGPARSE.py. Ensure that your current directory contains this file and that you spell it correctly.
  4. The argument name, as defined in our code is value with 2 hyphens before it. This is what we must type at the command line. If you misspell this or leave this out, you will get an error.
  5. The value of the parameter in this case is level. This is the actual value of the parameter. If you omit this, you will also get an error.
  6. Make sure that you put one space between each part of the above command when you practice this on your own machine.

If all goes well, you should see the following output when you run the script in the above manner. In this case we use the parameter values of level and william to test the program with 2 cases:

#Output
#Reverse is level. level IS a palindrome.
#Reverse is mailliw. william IS NOT A palindrome.

So that’s it! We used argparse to turn our python script into a command line tool! Neat right? You can find another great tutorial on how to parse a comma separated list with argparse HERE. Find the complete python argparse documentation HERE.

Thank you and good luck!👌👌👌

Tags: argparse
Previous Post

Python nltk Tokenize Example

Next Post

Python argparse Comma Separated List

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy