2012-03-31 5 views
1

誰もがClass too big and hard to add new featuresで質問に完全にunphasedですが、何らかの方法でコマンドラインオプションをメソッドに接続していますが、これに関するドキュメントは見つかりません。 optparse、または​​、またはsys.argvではありません。この質問は、メソッドとコマンドラインオプションの間に直接関係があることを意味します。私は何が欠けていますか?Pythonのコマンドライン引数はメソッドにどのように関係していますか?

答えて

1

私は単純にこのようなクラスを使用していますが、非常に良い考えではないようです。

class myprogram(object): 
    def __init__(self) 
     self.prepare() 
    def prepare(self): 
     # some initializations 
     self.prepareCommands() 
    def prepareCommands(self): 
     self.initCommand("--updateDatabase", self.updateDatabase) 
     self.initCommand("--getImages", self.getImages) 
     # and so on 
    def initCommand(self, cmd, func): 
     options = sys.argv 
     for option in options: 
      if option.find(cmd)!=-1: 
       return func() 
    # my commands 
    def updateDatabase(self): 
     #... 
    def getImages(self): 
     #... 
if __name__ == "__main__": 
    p = myprogram() 

EDIT1:ここに 私はちょうど実装きれいな方法:

myprogram.py:

from config import * # has settings 
from commands import * 

from logsys import log 
import filesys 

class myprogram(object): 
    def __init__(self): 
     log(_class=self.__name__, _func='__init__', _level=0) 
     log(_class=self.__name__, _func='__init__', text="DEBUG LEVEL %s" % settings["debug"], _level=0) 
     self.settings = settings 
     self.cmds = commands 
    def prepare(self): 
     log(_class=self.__name__, _func='prepare', _level=1) 
     self.dirs = {} 
     for key in settings["dir"].keys(): 
      self.dirs[key] = settings["dir"][key] 
      filesys.checkDir(self.dirs[key]) 

    def initCommands(self): 
     log(_class=self.__name__, _func='initCommands', _level=1) 
     options = sys.argv 
     for option in options: 
      for cmd in self.cmds.keys(): 
       if option.find(cmd) != -1: 
        return self.cmds[cmd]() 


if __name__ == '__main__':  
    p = myprogram() 
    p.prepare() 
    p.initCommands() 

commands.py:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 



commands = {} 
#csv 
import csvsys 
commands["--getCSV"] = csvsys.getCSV 
#commands["--getCSVSplitted"] = csvsys.getCSVSplitted 



# update & insert 
import database 
commands["--insertProductSpecification"] = database.insertProductSpecification 


# download 
import download 
commands["--downloadProductSites"] = download.downloadProductSites 
commands["--downloadImages"] = download.downloadImages 

# parse 
import parse 
commands["--parseProductSites"] = parse.parseProductSites 

EDIT2:私は今、更新してきたが私の質問は、より完全な例であなたの質問にリンクしましたClass too big and hard to add new features

+0

あなたの例の問題の1つは、--max-val 5や--treads = 5のような引数に値を与える方法がないということです。 –

+0

yes thats true実際、しかし私は特定の引数を必要としませんでした私の "コマンド"は、神のクラス自身が何をすべきかを知っていたからです。^^ –

+0

うわー、私はそのようなことをすることは考えていませんでした!面白い。 – weronika

4

これらの間にはストーンリンクはありません。あなたがリンクしている質問は、いくつかの異なることのうちの1つを行うことができるプログラムであり、コマンドライン引数はそれらの間で切り替わります。これらののものは、メソッドを使用してプログラムで実装されます。

これらの間に接着剤を書くには​​のようなものを使用していたという疑問が暗示されています。メソッドの使用は、特定のプログラムの実装の詳細です。

関連する問題