0

I am trying to execute a python script from within a Java program. I know that one of the way to do that is through the use of Runtime.getRuntime().exec() but the issue with this approach is that each time we use it we fork a new Process and hence I want to explore some other way also.

I want to use jython but I am unable to get an example which shows to do so. The examples which I saw were executing individual python commands but I want to execute the whole script at once just like we do it in Runtime.getRuntime().exec() but instead I want to do it through jython. Is there a way to do so? If there is any way then please provide me a simple example so that I can understand it.

Jason Donnald
  • 2,256
  • 9
  • 36
  • 49
  • You may want to check this other answer on [Calling a Python Script from Java](http://stackoverflow.com/a/10097910/697630) – Edwin Dalorzo Jan 29 '15 at 12:43
  • @EdwinDalorzo thanks for your comment. I have just one doubt. suppose if the python script does not contain any return command or print command (like the one shown in the example) will then also this approach work without any issue? – Jason Donnald Jan 29 '15 at 12:52
  • Your script will be executed whether it has output or not. If it produces no output I would assume it produces some kind of side effect which was the main cause why you invoked it. For instance, it may add a record to a database, or generate a file, etc. – Edwin Dalorzo Jan 29 '15 at 13:07
  • @EdwinDalorzo is the `ScriptContext` and `ScriptEngineManager` part of `jython` or standard `java`? If it is part of standard `java` then is there a similar way to do this in `jython` as well? – Jason Donnald Jan 30 '15 at 06:56
  • @EdwinDalorzo even though I haven't included jython in my project but import of `ScriptContext` and `ScriptEngineManager` does not given any error so I am confused as to whether it is part of jython or not – Jason Donnald Jan 30 '15 at 13:00
  • If you read my answer to the other question you will see that those classes you mention are part of [JSR-223](https://jcp.org/aboutJava/communityprocess/final/jsr223/index.html). If you read the specification you would understand. Those classes allows you to access any engine (e.g. JavaScript, Python, etc.). You use the classes to get access to such engine, but if you do not include the libraries of the engine you want to use, it would still fail. So you must include the Jython libraries if you want to get access to them through Java's script engine mechanisms. – Edwin Dalorzo Jan 30 '15 at 13:08
  • @EdwinDalorzo I wanted to know that how can I execute a specific function inside python script through the use of `ScriptEngine` and also pass parameters to that function? – Jason Donnald Apr 09 '15 at 16:52

0 Answers0