嗨,我尝试从java/war文件执行python。Tomcat可以访问此文件,因为它会生成它。作为 pi 或 root 用户,我可以毫无问题地执行生成的脚本文件。但是 tomcat8 进程无法正确运行脚本文件。
由于某种原因,我无法通过su tomcat8更改为tomcat8用户以尝试tomcat8用户可以,我不明白。
我使用此代码
public static void executePythonScript(String pathScriptFile) {
try{
File f = new File(pathScriptFile);
System.out.println(f.getAbsolutePath() +" exists:"+ f.exists());
ProcessBuilder pb = new ProcessBuilder("python", pathScriptFile);
Process p = pb.start();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);
}catch(Exception e){System.out.println(e);}
}
@RequestMapping(value="/api/togglegaragedoor")
public String toggleGarageDoor() {
try {
String prg = "#!/usr/bin/env pythonnnimport automationhat\nnautomationhat.relay.one.on()";
BufferedWriter out = new BufferedWriter(new FileWriter("/home/pi/Pimoroni/automationhat/examples/relay_on.py"));
out.write(prg);
out.close();
String prg2 = "#!/usr/bin/env pythonnnimport automationhat\nnautomationhat.relay.one.off()";;
BufferedWriter out2 = new BufferedWriter(new FileWriter("/home/pi/Pimoroni/automationhat/examples/relay_off.py"));
out2.write(prg2);
out2.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Api.executeCommand("which python");
Api.executePythonScript("/home/pi/Pimoroni/automationhat/examples/relay_on.py");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Api.executePythonScript("/home/pi/Pimoroni/automationhat/examples/relay_off.py");
return "toggled";
}
我没有收到任何错误。pi 应触发未单击的继电器。返回的值为 null。中继以 pi 用户身份单击。python exe是相同的(哪个python。
"/home/pi/Pimoroni/automationhat/examples/automationhat/init.py", lin e 354, in setup _ads1015 = ads1015(smbus.SMBus(1(( IOError: [errno 13] 权限被拒绝
GPIO.setup(self.pin, GPIO.OUT, initial=0)
运行时错误:无法访问/dev/mem。 尝试以根用户身份运行!
谢谢...这是需要将Tomcat8用户添加到没有密码的Sudoers文件中,并使用sudo执行python脚本...