如果我使用 curl 运行以下命令,则成功:
curl -XPOST 'localhost:9260/icrd_client_1' -d @clientmappings.json
该命令基于 json 文件在 elasticsearch 中创建索引。我得到了一个令人愉快的输出:
{"ok":true,"acknowledged":true}
我遇到的问题是从 python 脚本运行此命令时。
执行我的脚本后,我得到以下输出,而不是上面令人愉快的输出:
['curl', 'XPOST', 'http://localhost:9260/icrd_client_1 -d @clientmappings.json']
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
curl: (52) Empty reply from server
Traceback (most recent call last):
File "./elastic_ops.py", line 57, in <module>
output = run_curl(command, composed_url)
File "./elastic_ops.py", line 36, in run_curl
return subprocess.check_output(cmd)
File "/usr/lib/python2.7/subprocess.py", line 544, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['curl', 'XPOST', 'http://localhost:9260/icrd_client_1 -d @clientmappings.json']' returned non-zero exit status 52
输出不是一个单行 json 响应,因为我从 cmdline 的真正 curl 命令获得。我有两个问题:
1)我怎样才能捕获真正可爱的输出命令:{"ok":true,"acknowledged":true}
而不是关于传输的网络数据包等的胡言乱语。
2) 需要向 发送什么命令才能subprocess
像正常的 cmdline curl 命令一样工作。
我这样调用python脚本:
./elastic_ops.py create icrd_client_1 http://localhost:9260 clientmappings.json
这是我的python脚本的相关代码:
commandline_args = sys.argv
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]
print 'sending command: '
print cmd
return subprocess.check_output(cmd)
# create Index
# 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
print 'URL Request Being sent is:'
print '.... '+ composed_url
output = run_curl(command, composed_url)
print 'output:'
print output