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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rspvsanjay
    New Member
    • Sep 2016
    • 21

    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(ur l):
    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
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    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.getRunt ime().exec(comm and);

    (see javadoc for more infos)

    Comment

    • Oralloy
      Recognized Expert Contributor
      • Jun 2010
      • 988

      #3
      Try something like this, using (old-school) Runtime and Java IO:
      Code:
      //--command string to execute and capture output from.
      final String command = "sir_desc.py arg1 arg2";
      
      //--launch the command 
      final Process sirDesc = Runtime.getRuntime().exec(command);
      if (null == sirDesc)
        throw new NullPointerExeption("Bad things happened.");
      
      //--capture the output stream as an input to us...
      final java.io.InputStream inStreamBase = sirDesc.getInputStream();
      if (null == inStreamBase)
        throw new NullPointerExeption("Other bad sorts of things happened.");
      final java.io.InputStreamReader inStreamISR = new java.io.InputStreamReader(inStreamBase);
      final java.io.BufferedReader inStream = new java.io.BufferedReader(inStreamISR);
      
      //--capture all the output
      String inLine;
      final StringBuilder result = new StringBuilder();
      while (null != (inLine = inStream.readline()))
        result.append(inLine);
      That said, you might want to look into using ProcessBuilder, instead of Runtime:
      Code:
      //--command and arguments...
      final List<String> command = new List<String>();
      list.add("sir_desc.py");
      list.add("arg1");
      list.add("arg2");
      
      //--setup
      final ProcessBuilder pb = new ProcessBuilder();
      pb.command(command);
      
      //--launch the command 
      final Process sirDesc = pb.start();
      if (null == sirDesc)
        throw new NullPointerExeption("Bad things happened.");
      
      //--capture as above....
      Last edited by Oralloy; Sep 23 '16, 04:43 PM. Reason: copy-paste error in null check.

      Comment

      • rspvsanjay
        New Member
        • Sep 2016
        • 21

        #4
        thank you chaarmann :

        above python code able to run as below from commondprompt :

        C:\Python27>pyt hon
        Python 2.7.12 (v2.7.12:d33e0c f91556, 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.tutorialspo int.com/java/")
        'http://www.tutorialspo int.com/java/'
        >>>

        Comment

        • rspvsanjay
          New Member
          • Sep 2016
          • 21

          #5
          please write above command with Runtime.getRunt ime().exec(comm and);

          i want to know thar how argument can pass from java class ?

          Comment

          • rspvsanjay
            New Member
            • Sep 2016
            • 21

            #6
            //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(ur l):"+"\n return get_text(url)"
            +"\ndef main():"+"\n get_url_text(sy s.argv[1])"+"\nif __name__ == \"__main__\" : main()";

            BufferedWriter out = new BufferedWriter( new FileWriter("tes t234.py"));

            out.write(prg);

            out.close();

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

            //final ProcessBuilder pb = new ProcessBuilder( );
            ProcessBuilder pb = new ProcessBuilder( "python","test2 34.py","http://www.tutorialspo int.com/java/");

            final Process sirDesc = pb.start();

            final java.io.InputSt ream inStreamBase = sirDesc.getInpu tStream();

            final java.io.InputSt reamReader inStreamISR = new java.io.InputSt reamReader(inSt reamBase);

            final java.io.Buffere dReader inStream = new java.io.Buffere dReader(inStrea mISR);

            String inLine;

            final StringBuilder result = new StringBuilder() ;

            while (null != (inLine = inStream.readLi ne()))

            result.append(i nLine);

            System.out.prin tln("\n value is :\n "+result.toStri ng());
            }catch(Exceptio n e){}
            }
            }

            Comment

            • Oralloy
              Recognized Expert Contributor
              • Jun 2010
              • 988

              #7
              Attempt at diagnoses....

              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:
              Code:
              //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){}
               }
               }
              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

              Comment

              Working...