2

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 ?

AnujKu
  • 2,213
  • 5
  • 29
  • 40
  • Have you got any error? What is the output of you java program if you are not printing db connection ? – Nilesh Mar 07 '13 at 06: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: http://stackoverflow.com/questions/135035/python-library-path and print sys.path both from java & stand alone – GregHNZ Mar 07 '13 at 08:09

1 Answers1

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 !

AnujKu
  • 2,213
  • 5
  • 29
  • 40