Calling Python script from JAVA MySQLdb imports - java

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 ?

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 !

Related

Running python script that contains "behave" command in java

I am trying to run python script inside a java code by creating Process with Runtime
This is the contents of my java code:
String pythonPath = "/usr/local/bin/python3";
String runTestPath = "/Users/tuko/Documents/eclipse-workspace/WebLang_v2/runTests.py";
String[] cmd = new String[] {pythonPath, runTestPath};
Process process = Runtime.getRuntime().exec(cmd);
This is the contents of my python script:
import os
import time
import subprocess
try:
output = subprocess.check_output("behave",shell=True)
except Exception as e:
print(e)
This is the output:
Command 'behave' returned non-zero exit status 127.
Java doesn't recognize "behave" command. How to make this command recognizable by java

How can launch an external process from java and still be able to interact with this process?

My application should launch an external program to start recording the desktop.
I am using a simple program: recordmydesktop.
Launching the program works fine using ProcessBuilder.
My main issue is that I have to stop the recording. But I don't have access to the program anymore.
My first idea was to launch a terminal from java: bash did not stay open but xterm worked. First of all I would like to know why bash shell stay opened?
Then, I would like to find: How can I not use the xterm and still being able to stop the recording process? For example: send stop signal (Ctrl C) to the process.
Here is some sample code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class hh {
public static void main(String[] args) {
try {
Process process = new ProcessBuilder(new String[]{"/usr/bin/xterm" ,"recordmydesktop"}).start();
InputStream processIS = process.getInputStream();
InputStreamReader processISR = new InputStreamReader(processIS);
BufferedReader processBR = new BufferedReader(processISR);
String line;
System.out.println("Output of the record process is: ");
while ((line=processBR.readLine())!=null){
System.out.print(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Also, in this code, I am not able to get any line back. So my program does not know if the recordmydesktop is ok.
Ps: If you launch:
Process process = new ProcessBuilder(new String[]{"/usr/bin/xterm" ,"xterm"}).start();
Many xterm open instead of two. I create a loop that should not happen. This is not linked to my problem but if someone know the reason I am curious to know why.
Thanks for your help !
You can send a command to the process via the Output stream.
Process process ;
String command = "some command" ;
process.getOutputStream().writeBytes( command.getBytes() ) ;

unable to use taskkill.exe from a java process

I need to kill an external process on windows (WindowsXP 32bit) from my integration test. I thought I'd just use 'taskkill.exe' but I cannot seem to get it working. Basically, every time I kick off a 'taskkill.exe' process from java it returns exit value -1073741515, nothing is printed to std error/output.
To reproduce the problem I wrote this simple application:
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder();
//In my real code, I kill process by its pid. However below also shows the problem:
builder.command("taskkill.exe", "/?");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = r.readLine();
System.out.println("out:");
while(line != null) {
System.out.println(line);
line = r.readLine();
}
System.out.println(p.waitFor());
}
More data points:
-1073741515 apparently means "The application failed to initialize properly". Not very helpful for me though ;)
I've tried bunch of combinations of taskkill.exe parameters; I've tried prefixing the command with 'cmd', '/c'. Symptoms are exactly the same
I tried executing other windows programs that live under windows\system32 and I also get -10737...
Executing things like 'dir' or 'echo' works ok.
Any hints on what might be the problem?
Have you tried executing your application as a different user? If you're running your app with a plain batch file in windows, right click and select Run as administrator and see the results. It's likely the account you're running under doesn't have enough rights to execute native apps.

Linux Command is not giving an output invoked in java program

I am trying to invoke non linux command on linux using java code. The libraries required for that command are installed on my linux machine. Here is my java code which invokes the command using Runtime.getRuntime().exec();
The command reads the borcode from the image file and decodes it and shows the value on console.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class demo {
public static void main(String args[]){
getcodes();
}
public void getCodes(){
try
{
Process p;
String command[]=new String[3];
command[0]="dmtxread ";
command[1]="-n ";
command[2]="/home/administrator/sandip/xyz.tif";
System.out.println("Command : "+command[0]+command[1]+command[2]);
p=Runtime.getRuntime().exec(command);
System.out.println(p.waitFor());
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
System.out.print("Decoded :- "+line);
}
}catch(IOException e1) {
e1.getMessage();
e1.printStackTrace();
}catch(InterruptedException e2) {
e2.getMessage();
e2.printStackTrace();
}
}
}
As when I run this java code on linux I get following exception
part of exception is as follows:
Command : dmtxread -n /home/administrator/sandip/xyz.tif
java.io.IOException: Cannot run program "dmtxread ": java.io.IOException: error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:475)
at java.lang.Runtime.exec(Runtime.java:610)
at java.lang.Runtime.exec(Runtime.java:483)
at leadertechbarcode.TwoDBarCodeReadHelper.getCodes(TwoDBarCodeReadHelper.java:53)
Some times the program hangs afterinvoking the following code line
p=Runtime.getRuntime.exec(Command)
when I copy the command printed by the code and runs it on terminal it runs properly.
Please tell me friends in this problem.
Is there any other way to invoke this command using java?
Thanks You!
The Runtime.exec(String[]) method that you are using expects the first element to be the command and the following elements to be individual arguments. As such, if there are any spaces in them they will be escaped or quoted before being passed to the underlying operating system.
In your case, command[0] contains the name of the command followed by a space. This will cause the system to search for and execute a command which has that space in its name. This can not be found.
To solve this problem you should either remove the spaces surrounding the contents of each of the elements in command, or you can concatenate them manually and pass them in as a single string to the Runtime.exec(String) method instead. Note that you also have a space trailing your "-n" argument. You will likely need to remove that one as well.

Interact with java program using python [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calling Java app with “subprocess” from Python and reading the Java app output
Basically what I am looking for is, I want to interact with java program while its running using python so I can access its output and pass input to it.
I have managed to run a Java program using python. I want to know can i access the outputs of java program in my python program.
For example.
In java program: System.out.println("Enter no.");
In python i should be able to get "Enter no" as string and also pass value to java program from python.a
What I managed to do till no :
Python program :
import sys
import os.path,subprocess
def compile_java(java_file):
subprocess.check_call(['javac', java_file])
def execute_java(java_file):
java_class,ext = os.path.splitext(java_file)
cmd = ['java', java_class]
subprocess.call(cmd, shell=False)
def run_java(java_file):
compile_java(java_file)
execute_java(java_file)
Java Program :
import java.io.*;
import java.util.*;
class Hi
{
public static void main(String args[])throws IOException
{
Scanner t=new Scanner(System.in);
System.out.println("Enter any integer");
int str1=t.nextInt();
System.out.println("You entered"+str1);
}
}
Thanx :)
If all you need is to get the output from a non-interactive execution of your Java program, use subprocess.check_output instead of subprocess.call.
http://docs.python.org/library/subprocess.html
You need Python 2.7 or newer for check_output to be available.
If you need to interact with the Java program, you can do so using Popen.communicate, where you can read the process's output and send stuff to its input using file descriptors.
You can also use the pexpect python library to automate this kind of interaction, pexpect abstracts a lot of the legwork involved in using Popen.communicate.
Note that these techniques apply for any kind of executable you need your Python program to interact with, not just Java; as long as it uses stdin and stdout, using these calls should work for you.
The easiest way would be to use Jython, which is a complete Python implementation that runs in the JVM, and can interact with native Java code. But if you want to use CPython, and generally continue down the path you've sketched out above, you'll want to create a live Python Popen object that you can interact with. For example:
import sys
import os.path,subprocess
def compile_java(java_file):
subprocess.check_call(['javac', java_file])
def execute_java(java_file):
java_class,ext = os.path.splitext(java_file)
cmd = ['java', java_class]
return subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
def run_java(java_file):
compile_java(java_file)
process = execute_java(java_file)
for i in range(10):
process.stdin.write(str(i) + "\n")

Categories