python - 初学者 - 在程序中集成 optparse

标签 python optparse

我已经开始认真尝试学习一些 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()

最佳答案

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

我认为会有帮助的见解是 optparse 模块实际上并不能帮助您执行命令行上指定的操作。相反,它可以帮助您从命令行参数中收集信息,您以后可以根据这些信息采取行动。

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

(options, args) = parser.parse_args()

要实际根据这些信息采取行动,您将必须自己检查代码。我喜欢把这样的东西放在程序末尾的一个 block 中,which will only run if it is called from the command line .

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

为了更清楚地说明这是如何工作的,它有助于认识到您可以通过使用 sys.argv 完全不用 optparse 来做同样的事情。 .

import sys

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

然而,正如您可能看到的那样,这将是一个非常脆弱的实现。 optparse/argparse 能够处理更复杂的情况,而无需自己编写太多程序。

关于python - 初学者 - 在程序中集成 optparse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9845084/

相关文章:

python - 阻止 Visual Studio 的链接器在 Debug模式下查找 python39_d.lib

java - 将字符串中的正则表达式模式替换为取决于匹配的替换字符串

Python optparse 不接受选项

python - SQLAlchemy:触发器不在 INSERT 上触发

python - 有什么方法可以恢复 HG 或 GIT 变更集的下载?

python - 如何在 python 中从具有实数的数据帧制作包含复数的数据帧?

python - 如何使用 Python 的 optparse 格式化位置参数帮助?

python - 在 Python 中使用 optparse 定义变量

python - 暴力Python - OptParse 输出正确信息时遇到问题

ruby - 删除命令行开关