1、首先你的java服务环境部署,安装python
2、pythonPath为你python的安装路径
windows:python
linux:/data/anaconda/bin/python3.7
pyPath:调用python文件地址,可以直接放在java项目路径中,也可以放在本地文件夹
后面参数为调用python传递的参数
/**
* call python script
* @param paramsList --all need parameters to execute script
* @throws JSONException
*/
public static JSONObject runPyScriptByParams(String pyPath,String sourceShpPath,String depVar,String variables,String outputFile,String calculaterTypes) throws JSONException {
//log.info("excute runPyScriptByParams method ....");
System.out.println("excute runPyScriptByParams method ....");
JSONObject response = new JSONObject();
String[] parametersArr = new String[] {ToolsResource.pythonPath,pyPath,sourceShpPath,depVar,variables,outputFile,calculaterTypes};
log.info(Arrays.toString(parametersArr));
try {
Process pr = Runtime.getRuntime().exec(parametersArr);
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {// must have this, or the python script not execute
log.info("line == "+ line);//print python script execute info
if(line.toLowerCase().contains("error")) {
log.info("error == "+ line);
response.put("error",line);
}
}
in.close();
pr.waitFor();
response.put("success", "running sucess!");
} catch (Exception e) {
e.printStackTrace();
response.put("error", e.toString());
System.out.println(e);
}
return response;
}
3、python文件:main方法中获取传递过来的参数,调用方法执行
if __name__ == '__main__':
#LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
#logging.basicConfig(filename='wayhe_gwr.log', level=logging.DEBUG, format=LOG_FORMAT)
#logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=LOG_FORMAT)
#logging.FileHandler('gwrPython.log')
print("execute script main method ")
print(sys.getdefaultencoding())
for i in range(1, len(sys.argv)):
#print("get parameters == %s" % sys.argv[i])
if i == 1:
if '>>>>' in sys.argv[i]:
shpPath = sys.argv[i].replace('>>>>', ':') # windows path
else:
shpPath = sys.argv[i]
if i == 2:
depVarName = sys.argv[i]
if i == 3:
varilables = sys.argv[i]
if i == 4:
if '>>>>' in sys.argv[i]:
outputFile = sys.argv[i].replace('>>>>', ':') # windows path
else:
outputFile = sys.argv[i]
if i == 5:
calculaterTypes = sys.argv[i]
# {a:12456,b:jjshh,c:jhaoe,d:58dhah>88sdd}
# parase all parameter from java
print('shpPath===%s' % shpPath)
print('depVarName===%s' % depVarName)
print('varilables===%s' % varilables)
print('outputFile===%s' % outputFile)
print('calculaterTypes===%s' % calculaterTypes)
run = MyGWR()
try:
if calculaterTypes == "gwrRegress":
run.getGWR(shpPath, depVarName, varilables, outputFile)
else:
run.getOLS(shpPath, depVarName, varilables, outputFile)
except:
#print(sys.exc_info())
logging.info(sys.exc_info())