0

我有一个 Python 实用程序脚本,它在命令行中接受参数并针对名为Elasticsearch的开源搜索工具执行任务。

但简单地说,这是它目前的使用方式:

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

If you're using Python 2.7 or newer, try argparse. For older versions, try optparse

于 2013-10-29T13:52:42.377 回答
1

我会建议一个使用 python Dictionary 的简单优雅的解决方案,你可以使用字典key而不是 usingif语句,这不是最好的选择,我相信它只是更优雅一点。

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 回答
0

您也可以使用Getopt(它的工作方式与 GNU Getopt 类似)

于 2013-10-29T14:41:08.727 回答