3

I am calling a Python script from my Java code. This is the code :

 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class JavaRunCommand { public static void main(String args[]) throws IOException { // set up the command and parameter String pythonScriptPath = "my-path"; String[] cmd = new String[2]; cmd[0] = "python2.6"; cmd[1] = pythonScriptPath; // create runtime to execute external command Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(cmd); // retrieve output from python script BufferedReader bfr = new BufferedReader(new InputStreamReader( pr.getInputStream())); String line = ""; while ((line = bfr.readLine()) != null) { // display each output line form python script System.out.println(line); } } } 

python.py which works

 import os from stat import * c = 5 print c 

python.py which does not works

 import MySQLdb import os from stat import * c = 5 print c # some database code down 

So, I am at a critical stage where I have a deadline for my startup and I have to show my MVP project to the client and I was thinking of calling Python script like this. It works when I am printing anything without dB connection and MySQLdb library. But when I include them, it does not run the python script. Whats wrong here. Isnt it suppose to run the process handling all the inputs. I have MySQLdb installed and the script runs without the java code.

I know this is not the best way to solve the issue. But to show something to the client I need this thing working. Any suggestions ?

2
  • Have you got any error? What is the output of you java program if you are not printing db connection ? Commented Mar 7, 2013 at 6:05
  • Does your python script run from a command shell outside of java? Possibly Python in the command shell can't find the library. Check out this q: stackoverflow.com/questions/135035/python-library-path and print sys.path both from java & stand alone Commented Mar 7, 2013 at 8:09

1 Answer 1

0

So, I discovered that the issue was with the arguments that I was passing in Java to run the python program.

The first argument was - python 2.6 but it should have rather been just python not some version number because there was compatibility issue with MySQLdB and python.

I finally decided to use MySQL Python connector instead of MySQLdB in python code. It worked like charm and the problems got solved !

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.