我有一个 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