search
HomeBackend DevelopmentPython TutorialHow to use python command line parameter module argparse

The argparse module in Python is a command line argument parser that allows developers to easily write user-friendly command line interfaces.
The argparse module can automatically parse parameters from the command line, convert them into objects in Python, and provide some additional functions, such as automatically generating help documents, parameter type checking, etc.
The core of the argparse module is the ArgumentParser class. You can use this class to define the parameters and options that the program needs to receive.

Four steps to use argparse
Import the argparse package— —import argparse
Create ArgumentParser() object
Call the add_argument() method to add parameters
Parse command line parameters——Use parse_args() to parse the added parameters

Parameters of method add_argument:

def add_argument(self,
                 *name_or_flags: str,
                 action: Union[str, Type[Action]] = ...,
                 nargs: Union[int, str] = ...,
                 const: Any = ...,
                 default: Any = ...,
                 type: Union[(str) -> _T, (str) -> _T, FileType] = ...,
                 choices: Iterable[_T] = ...,
                 required: bool = ...,
                 help: Optional[str] = ...,
                 metavar: Union[str, Tuple[str, ...], None] = ...,
                 dest: Optional[str] = ...,
                 version: str = ...,
                 **kwargs: Any) -> Action

Example

parser=argparse.ArgumentParser("python")
parser.add_argument("-p", "--port",help="port to listen",type=int,nargs=5,dest="ports")
args=parser.parse_args()
print(args.ports,type(args.ports))

How to use python command line parameter module argparse

Explanation:

-p,–port, parameter name, help: Help information, type: the type of parameter being converted, nargs: read the number of command line parameters, multiple parameters are converted into a list, dest: the parsed parameter name

    parser.add_argument("-p", "--port",help="port to listen",default=8080,type=int,dest="ports")
    args=parser.parse_args()
    print(args.ports,type(args.ports))

default: default value

How to use python command line parameter module argparse

parser.add_argument("-p", "--port",help="port to listen",required=True,type=int,dest="ports")

required: Whether it is a required parameter or an optional parameter

How to use python command line parameter module argparse

    parser=argparse.ArgumentParser("python")
    parser.add_argument("-p", "--port",help="port to listen",required=True,type=int,dest="ports")
    parser.add_argument("-f","--flags",action="store_true")
    args=parser.parse_args()
    print(args.ports,type(args.ports),args.flags)

action: When with store_true, you pass in Corresponding parameter, the parameter is true, otherwise it is false, and the opposite is true for store_flase

How to use python command line parameter module argparse

parser.add_argument("-l",choices="12345")
choices,参数l的取值只能是12345,1,2,3,4,5,12,123,1234等,不能是其它,不能乱序

How to use python command line parameter module argparse

The above is the detailed content of How to use python command line parameter module argparse. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

Python List Concatenation Performance: Speed ComparisonPython List Concatenation Performance: Speed ComparisonMay 08, 2025 am 12:09 AM

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

How do you insert elements into a Python list?How do you insert elements into a Python list?May 08, 2025 am 12:07 AM

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.