Anuj Kulkarni
Anuj Kulkarni

Reputation: 2199

Calling Python script from JAVA MySQLdb imports

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 ?

Upvotes: 3

Views: 588

Answers (1)

Anuj Kulkarni
Anuj Kulkarni

Reputation: 2199

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 !

Upvotes: 0

Related Questions