6

我已经开始认真尝试学习一些 Python 作为我的第一门编程语言,并具有一些算法的基本知识。由于每个人都建议最好的开始方式是找到一些有用的事情来做,所以我决定做一个小脚本来管理我的存储库。

基本事项: - 启用/禁用 YUM 存储库 - 更改当前 YUM 存储库的优先级 - 添加/删除存储库

虽然解析文件和替换/添加/删除数据非常简单,但我正在努力(主要是因为可能缺乏知识)与“optparse”的单一事物......我想添加一个选项(-l)列出当前可用的存储库...我做了一个简单的函数来完成这项工作(不是很复杂),但我无法将它与 optparse 上的“-l”“连接”。任何人都可以提供有关如何做到这一点的示例/建议?

当前的脚本是这样的:

#!/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()

任何改进建议(文档、示例)都非常受欢迎。再次的主要目标是,当我执行时script.py -l它可以运行list_my_repos()

4

3 回答 3

6

使用解析选项optparse对我来说一直是相当不透明的。使用argparse有点帮助。

我认为会有所帮助的见解是,该optparse模块实际上并不能帮助您执行命令行上指定的操作。相反,它可以帮助您从命令行参数中收集信息,您可以稍后对其进行操作。

在这种情况下,您收集的信息存储在(options, args)您的行中的元组中:

(options, args) = parser.parse_args()

要真正根据这些信息采取行动,您将不得不自己检查代码。我喜欢把这样的东西放在程序末尾的一个块中,只有从命令行调用它才会运行

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

为了更清楚地说明它的工作原理,它有助于意识到你可以在没有 optparse 的情况下做同样的事情,通过使用sys.argv.

import sys

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

然而,正如您可能看到的那样,这将是一个非常脆弱的实现。能够处理更复杂的案例而无需自己进行过多的编程是optparse/argparse买给你的。

于 2012-03-23T19:33:07.007 回答
5

首先,optparse 文档说该库已弃用,您应该改用argparse。所以让我们这样做:

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

祝你学习 Python 好运 :)

于 2012-03-23T19:30:14.133 回答
3

您没有在代码中使用 -l 标志。该文档显示了如何检查标志是否存在。 http://docs.python.org/library/optparse.html

(options, args) = parser.parse_args()
if options.list:
   list_my_repos()
   return
于 2012-03-23T19:25:05.767 回答