Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Erry Kostala
Erry Kostala

Posted on

     

Python argparse cheat sheet

I have a confession to make: I never remember how to use argparse. Maybe it’s because I don’t use it often enough to have how it works memorized, but I certainly use it often enough that I’m annoyed every time I have to look it up. Argparse? More likeARGHparse. Either way, I thought I would make a handy cheat sheet that can be quickly looked up rather than reading the documentation.

Read a single argumentwith a value

parser.add_argument('--id', type=int, nargs=1)

Read a single argument with a default

parser.add_argument('--id', type=int, nargs='?', default=0)

Read a flag (boolean) argument

parser.add_argument('--delete', nargs='?', const=True, default=False)

Read multiple arguments

parser.add_argument('--ids', type=int, nargs='+')

Required arguments

parser.add_argument('--id', type=int, nargs=1, required=True)

That should cover the common use cases, hope this has been helpful for someone other than me!

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
davedavemckay profile image
David McKay
  • Joined

I like the use ofnargs=1 which will mean your script always deals with lists and keep the code consistent, rather than leaving it out and having some lists and some strings or ints.
nargs='?' andnargs='+' are new to me so thanks for them! I usenargs='*' a lot...

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I fight software and sometimes don't lose.
  • Location
    London
  • Joined

More fromErry Kostala

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp