2012-03-23 1 views
6

私は、アルゴリズムに関するいくつかの基本的な知識を持ち、最初のプログラミング言語としてPythonを学ぶための真剣な試みを始めました。私がリポジトリを管理するための小さなスクリプトを作成することを決めたのは、何か役に立つものを見つけることである。python - 初心者 - プログラム内のoptparseの統合

基本的な事柄: - 有効/無効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()を実行できるということです。

+0

可能であれば、 'argparse'を使うべきです。' optparseモジュールは廃止され、さらに開発されることはありません。 argparseモジュールを使用して開発を続けます」。 – Daenyth

答えて

6

optparseを使用してオプションの解析は常に私にはかなり不透明となっています。 argparseを使用すると少し役に立ちます。私が助けになると思い

洞察はoptparseモジュールが実際にあなたがコマンドラインで指定されたアクションを実行する助けにはならないということです。むしろ、コマンドライン引数から情報を収集するのに役立ちます。これは、後で実行することができます。この場合

、あなたが収集している情報は、あなたの行にタプル(options, args)に格納されています

(options, args) = parser.parse_args() 

実際、この情報に基づいて行動するには、あなたがあなた自身のチェックを行うために必要があるとしていますあなたのコード。私はプログラムの最後のブロックに、このようなものを入れたい、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/​​があなたを買収することです。

3

コードで-lフラグを使用していません。そのドキュメントには、フラグが存在するかどうかをチェックする方法が表示されます。 http://docs.python.org/library/optparse.html

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

はPanthrの例と並行してトリックを行いました。 – nmarques

5

まず第一に、optparse docsは、ライブラリが廃止されて言うと、あなたの代わりにargparseを使用する必要があります。それでは、それを行うみましょう:Pythonの学習を

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 

幸運:)

+0

良いことですが、残念ながら私はPython 2.6(RHEL6)を使っています。私は後でpython 2.7でopenSUSEボックスに行ってみましょう。 – nmarques