3

This is the first time I am trying python in java. I am trying to execute python script from my code as follows.

    Process process = Runtime.getRuntime().exec("python C:\\Users\\username\\Desktop\\demo\\filename.py");

But I am getting following exception

"Cannot run program "python": CreateProcess error=2, The system cannot find the file specified"

I have installed python. I am not sure why the file is not found. I tried to follow this link but it did not solve my issue.

Thanks in advance.

Edit 1

I tried the sample code given by "Viacheslav Vedenin", it worked when I executed my java(servlet) program. But when I ran the same function from JSP button click event, it did not work. It gave me following error

java.io.IOException: Cannot run program "python": CreateProcess error=2, The system cannot find the file specified 

Please help me to resolve this issue.

Tushar Thakur
  • 956
  • 3
  • 15
  • 32
  • You can add to the path Enviroment Variable the path of python soo thenyou will be able to execute a python command – MaQuiNa1995 Jun 30 '17 at 11:20

1 Answers1

3

Try to use full path to python, for example

Process process = Runtime.getRuntime().exec("C:\\Python\\python.exe  
          C:\\Users\\username\\Desktop\\demo\\filename.py");
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
  • I tried above sample and it worked when I ran my java program. But when I ran the same function from JSP button click event, it did not work. It gave me following error java.io.IOException: Cannot run program "python": CreateProcess error=2, The system cannot find the file specified – Tushar Thakur Jul 03 '17 at 05:00
  • You may have problem if you try to run program from JSP, see https://stackoverflow.com/questions/8877236/unable-to-execute-java-program-from-jsp-using-runtime-getruntime-exec , https://coderanch.com/t/282987/java/Runtime-getRuntime-exec-working-JSP – Slava Vedenin Jul 03 '17 at 11:50