Python - beginner - integrating optparse into a program

I started a serious attempt to learn Python as my first programming language with some basic knowledge of algorithms. Since everyone recommends that the best way to get started is to find something useful, I decided to make a small script to manage my repositories.

Key things: - Enable / disable YUM repositories - Change priority on current YUM repositories - Add / remove repositories

While parsing a file and replacing / adding / deleting data is quite simple, I am afraid (mainly due to lack of knowledge) with one thing with "optparse" ... I want to add to the option (- l), which lists the current available repositories ... I created a simple function that does this job (not very complicated), but I cannot "connect" it to "-l" on optparse. Can anyone provide examples / suggestions on how to do this?

The current script looks something like this:

#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import optparse import ConfigParse repo_file = "/home/nmarques/my_repos.repo" parser = optparse.OptionParser() parser.add_option("-e", dest="repository", help="Enable YUM repository") parser.add_option("-d", dest="repository", help="Disable YUM repository") parser.add_option("-l", dest="list", help="Display list of repositories", action="store_true") (options, args) = parser.parse_args() def list_my_repos() # check if repository file exists, read repositories, print and exit if os.path.exists(repo_file): config = ConfigParser.RawConfigParser() config.read(repo_file) print "Found the following YUM repositories on " + os.path.basename(repo_file) + ":" for i in config.sections(): print i sys.exit(0) # otherwise exit with code 4 else: print "Main repository configuration (" + repo_file +") file not found!" sys.exit(4) list_my_repos() 

Any suggestions for improvement (documents, examples) are welcome. The main goal once again is that when executing script.py -l it can run list_my_repos() .

+6
source share
3 answers

Parsing optparse using optparse have always been pretty opaque to me. Using argparse helps a bit.

The understanding, which I think will help, is that the optparse module does not actually help you perform the actions specified on the command line. Rather, it helps you gather information from command line arguments that you can act on later.

In this case, the information you collect is stored in a tuple (options, args) in your line:

 (options, args) = parser.parse_args() 

In order to actually work on this information, you will have to do your own code verification. I like to do such things in a block at the end of my program that will only be launched if it is called from the command line .

 if __name__ == '__main__': if options.list: list_my_repos() 

To make this a little easier, it helps to understand that you can do the same without optparse at all using sys.argv .

 import sys if __name__ == '__main__': if sys.argv[1] == '-l': list_my_repos() 

as you can see, however, this will be a very fragile implementation. The ability to handle more complex cases without having to do too much of your own programming is what optparse / argparse .

+6
source

First, optparse docs say the library is deprecated, and you should use argparse instead. So do this:

 import argparse parser = argparse.ArgumentParser() #Basic setup parser.add_argument('-l', action='store_true') #Tell the parser to look for "-l" #The action='store_true' tells the parser to set the value to True if there's #no value attached to it args = parser.parse_args() #This gives us a list of all the arguments #Passing the args -l will give you a namespace with "l" equal to True if args.l: #If the -l argument is there print 'Do stuff!' #Go crazy 

Good luck learning Python :)

+5
source

You do not use the -l flag in your code. The documentation shows how to check if a flag is present. http://docs.python.org/library/optparse.html

 (options, args) = parser.parse_args() if options.list: list_my_repos() return 
+3
source

Source: https://habr.com/ru/post/911532/


All Articles