6

アルゴリズムに関する基本的な知識を備えた最初のプログラミング言語として、Python を学ぶ真剣な試みを始めました。始めるには何か役に立つことを見つけるのが最善の方法だと誰もが勧めているので、リポジトリを管理するための小さなスクリプトを作成することにしました。

基本事項: - YUM リポジトリの有効化/無効化 - 現在の YUM リポジトリの優先度の変更 - リポジトリの追加/削除

ファイルの解析とデータの置換/追加/削除は非常に簡単ですが、「optparse」を使用して1つのことで苦労しています(主に知識不足で)...オプション(-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 に答える