3

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????)

1
  • Try using ProcessBuilder Commented Jul 31, 2012 at 16:12

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ok ! It works! I used getErrorStream() and getInputStream() to see what were the mistakes and correct them(python 2.7 instead of 2.5 => bad magic number in pyc, then bad parameter or paramater doesn't exist...)!
2

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" });

2 Comments

Indeed there is no more error,but no way to see if the script runs well or not, because I can't find the file that must have been generated (arg2 in my case). Moreover, if I just let ("python","script .pyc"), the result is the same (whereas when I launch the .pyc script in my terminal without args, a sort of "help" telling me the required param is printed).
Can i invoke a specific method of pyc and get results in return too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.