0

コマンドラインで引数を受け取り、Elasticsearchというオープン ソース検索ツールに対してタスクを実行する Python ユーティリティ スクリプトがあります。

簡単に言えば、現在の使用方法は次のとおりです。

Myscript.py create indexname http://localhost:9260
Myscript.py create indexname http://localhost:9260 IndexMap.json

スクリプトのユーザーがスクリプトへの引数の順序を覚える必要がないようにしたいと思います。スクリプトでこれを有効にするにはどうすればよいですか? 私は、Unix のような引数が渡されるという方針に沿って考えていました。例えば:

import os
import sys
import glob
import subprocess 

# collect command line arguments
commandline_args = sys.argv

# How to use this simple API:
#   create indexname http://localhost:9260 IndexMap.json

command_type = commandline_args[1]
index_name = commandline_args[2]
base_elasticsearch_url = commandline_args[3]
file_to_index = sys.argv[4] if len(sys.argv) > 4 else None


def run_curl(command, url):
    cmd = ['curl', command]
    url = url.split(' ')
    print 'sending command: '
    print cmd+url    
    return subprocess.check_output(cmd+url)

if (command_type == 'delete'):
    print 'About to run '+ command_type + ' on Index: ' + index_name
    command = '-XDELETE'
    composed_url = base_elasticsearch_url + '/' + index_name + '/'
    output = run_curl(command, composed_url)
    print 'output:'
    print output

# create Index # works!
# curl -XPOST 'localhost:9260/icrd_client_1 -d @clientmappings.json
if (command_type == 'create'):
    print 'About to run '+command_type+' for Index: '+index_name+' from filename: '+file_to_index
    command = '-XPOST'
    composed_url = base_elasticsearch_url + '/' + index_name +' -d ' + '@'+file_to_index
    output = run_curl(command, composed_url)
    print 'output:'
    print output
4

3 に答える 3

1

keyPython Dictionary を使用したシンプルでエレガントなソリューションを提案します。代わりにステートメントを使用して辞書を使用できます。ifこれは最良のオプションではありませんが、もう少しエレガントであると確信しています。

import sys

def func1():
    print "I'm func1"

def func2():
    print "I'm func2"

def func3():
    print "I'm func3"

def func4():
    print "I'm default!"

def main():

    myCommandDict = {"arg1": func1(), "arg2": func2(), "arg3": func3(), "default": func4()}

    commandline_args = sys.argv

    for argument in commandline_args[1]:
        if argument in myCommandDict:
            myCommandDict[argument]
        else:
            myCommandDict["default"]

if __name__ == "__main__":
    main()

Edit main は、次のオプションに置き換えることができます。

myCommandDict = {"arg1": func1, "arg2": func2, "arg3": func3, "default": func4}

commandline_args = sys.argv[1:]

for argument in commandline_args:
    if argument in myCommandDict:
        myCommandDict[argument]()
    else:
        myCommandDict["default"]()
于 2013-10-29T14:02:43.513 に答える
1

Python 2.7 以降を使用している場合は、 を試してくださいargparse。古いバージョンの場合は、試してくださいoptparse

于 2013-10-29T13:52:42.377 に答える