Question

I have a python compiled script (script.pyc , I haven't the .py file)that work well from my windows command prompt, and I want to execute it from my Java's application. I tried to use runtime() method :

        Runtime runtime = Runtime.getRuntime();
    runtime.exec(new String[] {"C:\\toto\\tools\\script.pyc" ,"arg","arg2" });

but I get an error :

Exception in thread "main" java.io.IOException: Cannot run program "C:\Nuance\VoCon Hybrid\SDK_v4_3\tools\clctodict.pyc": CreateProcess error=193, %1 n?est pas une application Win32 valid

The script work well in my terminal ("arg" is a txt file, "arg2" is the output name, and the script does its job without any problem).

I also try to launch my script with getDesktop() :

        File fie = new File("C:\\toto\\tools\\script.pyc" ,"arg","arg2");
    Desktop.getDesktop().open(fie); 

There is no problem, but I can't add argument, so I can just see a terminal windows opening during a few second before disappearing instantly. I have also tried to use JPython, without success too (maybe we can't use methode "execfile" on a .pyc????)

Was it helpful?

Solution

You can do something like

Process p = Runtime.getRuntime().exec(new String[]{"python.exe" ... other args)

Then you can invoke p.waitFor() to wait for the end of the process and p.exitValue() to test if the program exited successfully.

You can also get the output stream via p.getOutputStream() to retrieve the text printed by your python script

Please refer to the class documentation for further information : http://docs.oracle.com/javase/6/docs/api/java/lang/Process.html

OTHER TIPS

Just like you need a jvm to run a .class, you need a python interpreter to run a .pyc.

Try something like:

runtime.exec(new String[] {"c:\\Python26\\bin\\python.exe", "C:\\toto\\tools\\script.pyc" ,"arg","arg2" });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top