2012-12-31 25 views
1

我已成立了一個腳本argparse這給了我下面的命名空間中的位置參數:從argparse作爲函數名

Namespace(action='list', input='all', target='domain') 

我做了這是根據positionals叫了幾個功能,並在那一刻我有一個工作情況通過像這樣的代碼導語美其名曰:

if args.action == 'list': 
    if len(sys.argv) == 2: 
     parser.print_help() 
     sys.exit(0) 
elif args.target == 'domain': 
    domain_list() 
elif args.target == 'forwarding': 
    forwarding_list() 
elif args.target == 'transport': 
    transport_list() 
elif args.target == 'user': 
    user_list() 
else: 
    all_list() 

我知道這是可以做到的方式,方法比這更好;但是由於我對Python的知識有限,似乎無法解決這個問題。

回顧:我想是這樣,如果在所有可能的(僞)

if args.action == 'add': 
    target = args.target 
    target_add() 

其中target_add()有點像domain_add()

在此先感謝!

+0

會是這樣的幫助呢? http://stackoverflow.com/questions/3061/calling-a-function-from-a-string-with-the-functions-name-in-python – favoretti

+0

你可能會對[docopt]感興趣(https:// github .com/docopt/docopt),它是「爲人類辯護」。 –

+0

@favoretti;是的,據我所見,這很像這個問題的公認答案:) @PauloScardine在閱讀了很多關於它的文檔和大量問題後,我瞭解了argparse,但是,我陷入了困境關於python代碼本身的內部工作^ _^ –

回答

0

這聽起來像操作可能是:listadd,而target可能是domainforwardingtransport,或user。是的,如果您不得不手動列出每個選項組合將執行的操作,那麼您最終會得到很多if..then..else代碼。

這裏是爲了簡化這個辦法:

  • 使用itertools.product產生的 選擇所有可能的組合。
  • 使用白名單調度字典將選項映射到函數。密鑰是2元組,如('domain','list')('transport','add')。這些值是關聯的函數對象。

import itertools as IT 

targets = 'domain forwarding transport user'.split() 
actions = 'list add'.split() 

dispatch = {key:globals()['%s_%s' % key] for key in IT.product(targets, actions)} 

# This calls the function specified by (target, action). 
# The `dict.get` method is used so that if the key is not in `dispatch`, the `all_list` function is called. 
dispatch.get((args.target, args.action), all_list)() 
+0

真棒,這對我來說就像一個魅力,並且也將我的代碼削減了一半! :) –