473,399 Members | 2,159 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

how to call given python code from java class then get result as string

import urllib2
import re

def get_text(str):
return str

def get_url_text(url):
return get_text(url)





actual python code i attached into sir_desc.txt file and i want to run this program from java class that python code takes one URL as a argument and return string as out put

please tell me how that is possible from java
Sep 23 '16 #1

✓ answered by Oralloy

Try something like this, using (old-school) Runtime and Java IO:
Expand|Select|Wrap|Line Numbers
  1. //--command string to execute and capture output from.
  2. final String command = "sir_desc.py arg1 arg2";
  3.  
  4. //--launch the command 
  5. final Process sirDesc = Runtime.getRuntime().exec(command);
  6. if (null == sirDesc)
  7.   throw new NullPointerExeption("Bad things happened.");
  8.  
  9. //--capture the output stream as an input to us...
  10. final java.io.InputStream inStreamBase = sirDesc.getInputStream();
  11. if (null == inStreamBase)
  12.   throw new NullPointerExeption("Other bad sorts of things happened.");
  13. final java.io.InputStreamReader inStreamISR = new java.io.InputStreamReader(inStreamBase);
  14. final java.io.BufferedReader inStream = new java.io.BufferedReader(inStreamISR);
  15.  
  16. //--capture all the output
  17. String inLine;
  18. final StringBuilder result = new StringBuilder();
  19. while (null != (inLine = inStream.readline()))
  20.   result.append(inLine);
  21.  
That said, you might want to look into using ProcessBuilder, instead of Runtime:
Expand|Select|Wrap|Line Numbers
  1. //--command and arguments...
  2. final List<String> command = new List<String>();
  3. list.add("sir_desc.py");
  4. list.add("arg1");
  5. list.add("arg2");
  6.  
  7. //--setup
  8. final ProcessBuilder pb = new ProcessBuilder();
  9. pb.command(command);
  10.  
  11. //--launch the command 
  12. final Process sirDesc = pb.start();
  13. if (null == sirDesc)
  14.   throw new NullPointerExeption("Bad things happened.");
  15.  
  16. //--capture as above....
  17.  

6 2688
chaarmann
785 Expert 512MB
It doesn't matter if it is python or another language.
If you can run it by typing a command string on the shell, then you can run it (and grab the output afterwards) with following Java command:

Runtime.getRuntime().exec(command);

(see javadoc for more infos)
Sep 23 '16 #2
Oralloy
988 Expert 512MB
Try something like this, using (old-school) Runtime and Java IO:
Expand|Select|Wrap|Line Numbers
  1. //--command string to execute and capture output from.
  2. final String command = "sir_desc.py arg1 arg2";
  3.  
  4. //--launch the command 
  5. final Process sirDesc = Runtime.getRuntime().exec(command);
  6. if (null == sirDesc)
  7.   throw new NullPointerExeption("Bad things happened.");
  8.  
  9. //--capture the output stream as an input to us...
  10. final java.io.InputStream inStreamBase = sirDesc.getInputStream();
  11. if (null == inStreamBase)
  12.   throw new NullPointerExeption("Other bad sorts of things happened.");
  13. final java.io.InputStreamReader inStreamISR = new java.io.InputStreamReader(inStreamBase);
  14. final java.io.BufferedReader inStream = new java.io.BufferedReader(inStreamISR);
  15.  
  16. //--capture all the output
  17. String inLine;
  18. final StringBuilder result = new StringBuilder();
  19. while (null != (inLine = inStream.readline()))
  20.   result.append(inLine);
  21.  
That said, you might want to look into using ProcessBuilder, instead of Runtime:
Expand|Select|Wrap|Line Numbers
  1. //--command and arguments...
  2. final List<String> command = new List<String>();
  3. list.add("sir_desc.py");
  4. list.add("arg1");
  5. list.add("arg2");
  6.  
  7. //--setup
  8. final ProcessBuilder pb = new ProcessBuilder();
  9. pb.command(command);
  10.  
  11. //--launch the command 
  12. final Process sirDesc = pb.start();
  13. if (null == sirDesc)
  14.   throw new NullPointerExeption("Bad things happened.");
  15.  
  16. //--capture as above....
  17.  
Sep 23 '16 #3
thank you chaarmann :

above python code able to run as below from commondprompt :

C:\Python27>python
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (
Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import test432
>>> test432.get_url_text("http://www.tutorialspoint.com/java/")
'http://www.tutorialspoint.com/java/'
>>>
Sep 23 '16 #4
please write above command with Runtime.getRuntime().exec(command);

i want to know thar how argument can pass from java class ?
Sep 23 '16 #5
//thank you sir Oralloy
//plese tell me where i have done mistake in below program
import java.io.*;
class test234
{
public static void main(String a[])
{
try{
String prg = "import sys\ndef main():\ndef get_text(str):"+"\n return str"+
"\ndef get_url_text(url):"+"\n return get_text(url)"
+"\ndef main():"+"\n get_url_text(sys.argv[1])"+"\nif __name__ == \"__main__\": main()";

BufferedWriter out = new BufferedWriter(new FileWriter("test234.py"));

out.write(prg);

out.close();

//final String command = "test234.py http://www.tutorialspoint.com/java/";

//final ProcessBuilder pb = new ProcessBuilder();
ProcessBuilder pb = new ProcessBuilder("python","test234.py","http://www.tutorialspoint.com/java/");

final Process sirDesc = pb.start();

final java.io.InputStream inStreamBase = sirDesc.getInputStream();

final java.io.InputStreamReader inStreamISR = new java.io.InputStreamReader(inStreamBase);

final java.io.BufferedReader inStream = new java.io.BufferedReader(inStreamISR);

String inLine;

final StringBuilder result = new StringBuilder();

while (null != (inLine = inStream.readLine()))

result.append(inLine);

System.out.println("\n value is :\n "+result.toString());
}catch(Exception e){}
}
}
Sep 24 '16 #6
Oralloy
988 Expert 512MB
rspvsanjay,

When you have code to share, please put it in [code] brackets. You will see a "button" just above the text input area.

Your code looks something like this:
Expand|Select|Wrap|Line Numbers
  1. //thank you sir Oralloy
  2.  //plese tell me where i have done mistake in below program
  3.  import java.io.*;
  4.  class test234
  5.  {
  6.  public static void main(String a[])
  7.  {
  8.  try{
  9.  String prg = "import sys\ndef main():\ndef get_text(str):"+"\n return str"+
  10.  "\ndef get_url_text(url):"+"\n return get_text(url)"
  11.  +"\ndef main():"+"\n get_url_text(sys.argv[1])"+"\nif __name__ == \"__main__\": main()";
  12.  
  13.  BufferedWriter out = new BufferedWriter(new FileWriter("test234.py"));
  14.  
  15.  out.write(prg);
  16.  
  17.  out.close();
  18.  
  19.  //final String command = "test234.py http://www.tutorialspoint.com/java/";
  20.  
  21.  //final ProcessBuilder pb = new ProcessBuilder();
  22.  ProcessBuilder pb = new ProcessBuilder("python","test234.py","http://www.tutorialspoint.com/java/");
  23.  
  24.  final Process sirDesc = pb.start();
  25.  
  26.  final java.io.InputStream inStreamBase = sirDesc.getInputStream();
  27.  
  28.  final java.io.InputStreamReader inStreamISR = new java.io.InputStreamReader(inStreamBase);
  29.  
  30.  final java.io.BufferedReader inStream = new java.io.BufferedReader(inStreamISR);
  31.  
  32.  String inLine;
  33.  
  34.  final StringBuilder result = new StringBuilder();
  35.  
  36.  while (null != (inLine = inStream.readLine()))
  37.  
  38.  result.append(inLine);
  39.  
  40.  System.out.println("\n value is :\n "+result.toString());
  41.  }catch(Exception e){}
  42.  }
  43.  } 
  44.  
Since you can see what I see, would you answer your question? This needs to be reasonably formatted for people to read and understand. In the future, please do so.

Please read: https://bytes.com/forum/faq.php?faq=posting_guidelines

Now that we've discussed that, follow-up questions are quite reasonable, but you have to tell me your problem and what you've tried. When all you do is give me code and ask what is wrong, I have no idea.

That said, I will make a few guesses:
  1. You are dynamically creating and executing a python program from within the Java.
  2. Your Python file executes perfectly.
  3. Your code executes with no exceptions.
  4. The code output is just the header (" value is :") followed by an empty string.
  5. You read and understood the Java documentation for the ProcessBuilder and Process classes.
  6. The try/catch block is only there to suppress error print-out when the program executes correctly.
  7. You understand how sub-processes are created.
  8. You understand how file handles and pipes are used to communicate with sub-processes.

Since I think that I may have overstepped my bounds in helping you with what looks like it is homework, I will try to help you diagnose and understand what you have:
  1. Verify that the Java code correctly compiles.
  2. Verify that the Python program is correctly created.
  3. Verify that the created Python program executes as required; do this by running it from the command line.
  4. Run your Java program and verify that no exceptions or errors occur.
  5. If you are using Eclipse, IntelliJ, or other IDE execute your program one line at a time and verify that good things happened.
  6. If you are using command line only, then you might want to put a printout after each statement in your program.
  7. In general, verify that each line of your code executes correctly, and the resulting machine state is exactly what you expect.

Here are a few links that I think you should read. The first has the example which was used as a basis of my first reply to you.
  1. http://docs.oracle.com/javase/7/docs...ssBuilder.html
  2. Or: http://docs.oracle.com/javase/7/docs...ssBuilder.html
  3. http://docs.oracle.com/javase/7/docs...g/Process.html
  4. http://docs.oracle.com/javase/7/docs...Exception.html

Once you've done that, I think you will have answered your own question, and solved the problem.

* IDE - Integrated Development Environment
Sep 24 '16 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Fu Bo Xia | last post by:
the java.lang.Object.forName method takes a java class name and returns a Class object associated with that class. eg. Class myClass = Object.forName("java.lang.String"); by if i only know the...
4
by: angel | last post by:
A java runtime environment includes jvm and java class (for example classes.zip in sun jre). Of course jython need jvm,but does it need java class. Thanx
13
by: Ajay | last post by:
hi! can you call a Python application from a Java program? does this require any additional package to be installed? thanks cheers
9
by: F. GEIGER | last post by:
I've dev'ed a Python prototype of an app, that besides the internals making it up has a gui. While test-driven dev'ing the app's internals in Python is fun as usual, dev'ing the GUI is not so...
3
by: Rajesh | last post by:
Hi, I am using iplanet webserver 4.1. I want to call a java class from ssjs file. But I am not getting the result. I have created a java class file and put it in the folder...
28
by: liorm | last post by:
Hi everyone, I need to write a web app, that will support millions of user accounts, template-based user pages and files upload. The client is going to be written in Flash. I wondered if I coudl...
3
by: evelyne0510 | last post by:
Hi all, I have created a XML-RPC model (with server and client) written in Java. I want to call the methods in another XML-RPC model written in Python. I know that in Java, I can use like...
16
by: Amir Michail | last post by:
Hi, It seems to me that measuring productivity in a programming language must take into account available tools and libraries. Eclipse for example provides such an amazing IDE for java that it...
1
by: skchonghk | last post by:
Dear all smart experts, I write a simple Java UDF, which should run on DB2 v8 on AIX. But it can't load the Java class. Help ugently needed!! Thanks! I develop and deploy the Java UDF with...
1
by: datulaida | last post by:
Hi.. How to connect Python with Java. This is my Python program. i use jpype to connect Python with Java. Code: ( text ) 1. from jpype import * 2. startJVM("d:/Program...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.