DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • 5 Simple Steps To Get Your Test Suite Running in Heroku CI
  • Instant Integrations With API and Logic Automation
  • Mastering Git
  • Terraform Best Practices: The 24 Practices You Should Adopt

Trending

  • Part 1: Building Governed MCP Tool Services With Quarkus LangChain4j and Goose
  • OpenCode: Setting Up an Open-Source AI Coding Assistant
  • How You Clear Your HTML5 Canvas Matters
  • How to Keep AI Agents From Going Rogue Using Docker Sandbox

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Multi-Level Argparse in Python (Parsing Commands Like Git)

Multi-Level Argparse in Python (Parsing Commands Like Git)

By 
Chase Seibert
·
Apr. 03, 14 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
18.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

It’s a common pattern for command line tools to have multiple subcommands that run off of a single executable. For example, git fetch origin and git commit --amend both use the same executable /usr/bin/git to run. Each subcommand has its own set of required and optional parameters.

This pattern is fairly easy to implement in your own Python command-line utilities using argparse. Here is a script that pretends to be git and provides the above two commands and arguments.

#!/usr/bin/env python

import argparse
import sys


class FakeGit(object):

    def __init__(self):
        parser = argparse.ArgumentParser(
            description='Pretends to be git',
            usage='''git <command> [<args>]

The most commonly used git commands are:
   commit     Record changes to the repository
   fetch      Download objects and refs from another repository
''')
        parser.add_argument('command', help='Subcommand to run')
        # parse_args defaults to [1:] for args, but you need to
        # exclude the rest of the args too, or validation will fail
        args = parser.parse_args(sys.argv[1:2])
        if not hasattr(self, args.command):
            print 'Unrecognized command'
            parser.print_help()
            exit(1)
        # use dispatch pattern to invoke method with same name
        getattr(self, args.command)()

    def commit(self):
        parser = argparse.ArgumentParser(
            description='Record changes to the repository')
        # prefixing the argument with -- means it's optional
        parser.add_argument('--amend', action='store_true')
        # now that we're inside a subcommand, ignore the first
        # TWO argvs, ie the command (git) and the subcommand (commit)
        args = parser.parse_args(sys.argv[2:])
        print 'Running git commit, amend=%s' % args.amend

    def fetch(self):
        parser = argparse.ArgumentParser(
            description='Download objects and refs from another repository')
        # NOT prefixing the argument with -- means it's not optional
        parser.add_argument('repository')
        args = parser.parse_args(sys.argv[2:])
        print 'Running git fetch, repository=%s' % args.repository


if __name__ == '__main__':
    FakeGit()

The argparse library gives you all kinds of great stuff. You can run ./git.py --help and get the following:

usage: git <command> [<args>]

The most commonly used git commands are:
   commit     Record changes to the repository
   fetch      Download objects and refs from another repository

Pretends to be git

positional arguments:
  command     Subcommand to run

optional arguments:
  -h, --help  show this help message and exit

You can get help on a particular subcommand with ./git.py commit --help.

usage: git.py [-h] [--amend]

Record changes to the repository

optional arguments:
  -h, --help  show this help message and exit
  --amend

Want bash completion on your awesome new command line utlity? Try argcomplete, a drop in bash completion for Python + argparse.

Command (computing) Python (language) Git

Published at DZone with permission of Chase Seibert. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • 5 Simple Steps To Get Your Test Suite Running in Heroku CI
  • Instant Integrations With API and Logic Automation
  • Mastering Git
  • Terraform Best Practices: The 24 Practices You Should Adopt

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook