目录
前提描述
本文只解决在本地执行程序成功,部署到服务器上后,服务器上Tomcat执行cmd运行python不成功问题。(服务器系统为windows Server 2012 R2)
利用java调用服务器上的程序,代码如下:
public void getPythonRes(Data data, JSONObject json) throws Exception{
// TODO Auto-generated method stub
Process proc;
List jsonList = new ArrayList();
try {
String str="python C:/test.py";
proc = Runtime.getRuntime().exec(str);
//用输入输出流来截取结果
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
String message=new String();
int flag=0;
while ((line = in.readLine()) != null) {
flag=1;
System.out.println(line);
message+=line;
message+="\n";
jsonList.add(line);
}
//返回json
if(flag==1){
json.put("content","有");
}else {
json.put("content","无");
}
json.put("aaData",jsonList);
//json设置完毕
//收尾
in.close();
proc.waitFor();
} catch (IOException e) {
e.printStackTrace();
json.put("wrong",e);
} catch (InterruptedException e) {
e.printStackTrace();
json.put("wrong",e);
}
}
可能发生的错误
错误一:
java.io.IOException: Cannot run program “python”: CreateProcess error=2, 系统找不到指定的文件。
【将”python“改为”cmd /c python“后,虽然不报错,但是仍然不能运行python文件】
【将”python“改为”
C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python310\\python.exe
“(绝对路径),会出现以下错误二】
错误二:
CreateProcess error= 5,拒绝访问
原因分析
与在本地运行权限不同,在服务器中运行的tomcat的用户权限不够
解决方法
服务器中打开Tomcat程序,点击”Log On“标签
勾选”Local System accoun“,应用并重新启动tomcat,即可成功运行python程序