我有一个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
答案 0 :(得分:1)
答案 1 :(得分:1)
我建议使用python Dictionary一个简单优雅的解决方案,你可以使用字典key
而不是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"]()
答案 2 :(得分:0)
您也可以使用Getopt(它的工作方式与GNU Getopt类似)