I've started a serious attempt to learn some Python as my first programming language with some basic knowledge on algorithms. Since everyone recommends that the best way to start is to find something useful to do, I've decided to do a small script to manage my repositories.
Basic things: - Enable/Disable YUM repositories - Change priority on current YUM repositories - Add/Remove repositories
While parsing the file and replace/add/remove data is quite simple, I'm struggling (mainly with maybe lack of knowledge) with a single thing with 'optparse'... I want to add to an option (-l) which lists the current available repositories... I've made a simple function that does this job (not something very elaborate), but I'm unable to 'connect' it with the '-l' on optparse. Anyone could provide examples/suggestions on how to make this?
The current script is 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 to improve (docs, examples) are most welcome. The main goal once more, is that when I execute script.py -l
it can run list_my_repos()
.
argparse
when possible -- ` The optparse module is deprecated and will not be developed further; development will continue with the argparse module.` – Outgoings