I have a Python utility script that accepts arguments in the commandline and executes tasks against an open source search tool called Elasticsearch.
But simply put, here is how it's currently being used:
Myscript.py create indexname http://localhost:9260
Myscript.py create indexname http://localhost:9260 IndexMap.json
I would like to make it so that the user of the script doesn't have to remember the order of the arguments to the script. How can I enable this in my script? I was thinking along the lines of a Unix-like argument passing. For example:
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