0

How can I build the following with argparse:

Synopsis: python3 program.py [operation] [options] target

Operations: install, uninstall, update or remove (you choose one).

I want the operations to have their own set of options. I'm not looking for specific code, just some general guidance.

1

2 Answers 2

3

It sounds like you want subparsers. The dest='subparser_name' bit allows you to tell which subparser has been called.

import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subparser_name')
install_parser = subparsers.add_parser('install')
install_parser.add_argument('target')
subparsers.add_parser('uninstall')

print(parser.parse_args(['uninstall']))
print(parser.parse_args(['install', 'target=foo']))
print(parser.parse_args(['uninstall', 'install', 'target=foo']))

Output:

Namespace(subparser_name='uninstall')
Namespace(subparser_name='install', target='target=foo')
usage: test.py [-h] {install,uninstall} ...
test.py: error: unrecognized arguments: install target=foo
Sign up to request clarification or add additional context in comments.

Comments

0

Here how I am doing for similar requirements, However this might be a very basic method and beginner level:
Example (getopt):

#!/usr/bin/python
import sys, getopt
def main(argv):
   arg=''
   try:
      opts, args = getopt.getopt(argv,"i:u:r:",["install=","update=","remove="])
   except getopt.GetoptError:
      print('test.py -i <myinput>')
      sys.exit(2)
   for opt, arg in opts:
      if opt in ("-i", "--install"):
         #Your operation
         print('installing something based on my input',arg)
         sys.exit()
      elif opt in ("-u", "--update"):
         #Your operation
         print('updating something based on my input',arg)
         sys.exit()
      elif opt in ("-r", "--remove"):
         #Your operation
         print('removing something based on my input',arg)
         sys.exit()  

if __name__ == "__main__":
   main(sys.argv[1:])

Reference: Link

Usage:

python test.py -i myinput

Output:

installing something based on my input myinput

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.