Results 1 to 7 of 7
  1. #1
    JavaN00bie is offline Member
    Join Date
    Jun 2011
    Posts
    21
    Rep Power
    0

    Default Running a Python Script in Java

    Hi everyone. So some of you may remember my problem with extracting individual documents from zip archives using java. Well, traversing the directory structure within the zip files was getting a little too complicated, so instead of trying to re-invent the wheel I just decided to get a python script from a friend who had used it previously for another program. Now I am trying to integrate this python script into my code within java, and I am at a loss as to what to do. I thought it would the same as running a .exe file from the command line, but it just doesn't seem to be working for me.

    Here is the entirety of my code:

    Java Code:
    import java.io.*;
    
    
    public class SPImageExtractor
    {
    	public static void main(String[] args) throws IOException
    	{
    		try 
    		{
                Runtime rt = Runtime.getRuntime();
                Process pr = rt.exec("C:/Documents and Settings/user/Tools/ofc.exe");
    
                BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    
                String line=null;
    
                while((line=input.readLine()) != null) 
                {
                    System.out.println(line);
                }
    
                int exitVal = pr.waitFor();
                System.out.println("Exited with error code "+ exitVal);
    
            } 
    		catch(Exception e) 
    		{
                System.out.println(e.toString());
                e.printStackTrace();
            }
            
            try 
            {
            	Runtime rt2 = Runtime.getRuntime();
            	Process pr2 = rt2.exec("cmd /c C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Image-Extractor2.py");
            	pr2.waitFor();
            	BufferedReader br = new BufferedReader(new InputStreamReader(pr2.getInputStream()));
            	String line = "";
            	while ((line = br.readLine()) != null) 
            	{
            	    System.out.println(line);
            	}
            } 
            catch(Exception e) 
            {
                System.out.println(e.toString());
                e.printStackTrace();
            }}}
    Basically, the code takes a bunch of word 97-2003 documents and bulk converts them using an external application to word 2007 (.docx) format --> the first try block. On the second it's supposed to basically do the same thing in terms of calling something outside of java from the command line, only thing is, the script itself is supposed to take the converted .docx documents and extract all the images from them, but nothing happens when the code is executed. And I know the python script works because when I execute it directly from the command line myself, all the images get extracted, no problem. The annoying part is, Java gives me no error messages or anything. So any ideas what I could be doing wrong?
    Last edited by JavaN00bie; 06-20-2011 at 07:07 PM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Are you sure that you want to use cmd as your executable program in your second RunTime#exec statement? Shouldn't that instead be Python.exe or something similar?

  3. #3
    JavaN00bie is offline Member
    Join Date
    Jun 2011
    Posts
    21
    Rep Power
    0

    Default

    I'm not really a python expert myself. But from what I've seen, these scripts are most often run with cmd.

    I mean to run it outside of java, all I do is go to cmd and type (including the quotes):

    "C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Image-Extractor2.py"

    and it works fine :/

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by JavaN00bie View Post
    I'm not really a python expert myself. But from what I've seen, these scripts are most often run with cmd.
    Are you 100% sure about this, that the interpreter is not being called in the background by the OS?


    I mean to run it outside of java, all I do is go to cmd and type (including the quotes):

    "C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Image-Extractor2.py"

    and it works fine :/
    Yes, but you likely have a file association in your operating system that associates py with the Python interpreter. I don't use Python, but it just seems to make sense that you should have your exec method call the python interpreter and pass the script to the interpreter.

  5. #5
    JavaN00bie is offline Member
    Join Date
    Jun 2011
    Posts
    21
    Rep Power
    0

    Default

    That might be the case.

    But I have no idea what to change it to. I have Python 2.6 and Jython 2.5.2 on my computer so instead of cmd I tried:

    python.exe
    jython.exe
    python26.exe
    python2.6.exe
    python 2.6.exe
    jython2.5.2.exe

    none of those worked

    And I looked around google and some of the examples I found seemed to work with using cmd. So I don't understand why mine isn't working :/

  6. #6
    JavaN00bie is offline Member
    Join Date
    Jun 2011
    Posts
    21
    Rep Power
    0

    Default

    After some trial and error I finally found out about 'Jython' and used the PythonInterpreter to try and run the script. However, upon trying to run it, I am getting an error within the Python Script. This is odd because when I try run the script outside of Java (Eclipse IDE in this case), the script works fine and does exactly what I need it to (extract all the images from the .docx files stored in its same directory). So I'm not sure why this isn't working, does anyone have an idea?

    Java:

    Java Code:
    import java.io.IOException;
    import org.python.core.PyInteger;
    import org.python.core.PyObject;
    import org.python.core.PyException;
    import org.python.util.PythonInterpreter;
    
    public class SPImageExtractor
    {
        public static void main(String[] args) throws PyException
        {   
            try
            {
                PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
                PythonInterpreter interp = new PythonInterpreter();
                interp.execfile("C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Image-Extractor2.py");
            }
            catch(Exception e)
            {
                System.out.println(e.toString());
                e.printStackTrace();
            }
        }
    }
    ------------------------------------------------
    Java Error regarding Python Script:

    Traceback (most recent call last):
    File "C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Image-Extractor2.py", line 19, in <module>
    thisDir,_ = path.split(path.abspath(argv[0]))
    IndexError: index out of range: 0
    Traceback (most recent call last):
    File "C:/Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Image-Extractor2.py", line 19, in <module>
    thisDir,_ = path.split(path.abspath(argv[0]))
    IndexError: index out of range: 0
    ------------------------------------------------

    Python:

    Java Code:
    from os import path, chdir, listdir, mkdir
    from sys import argv
    from zipfile import ZipFile
    from time import sleep
    
    #A few notes -
    #(1) when I do something like " _,variable = something ", that is because
    #the function returns two variables, and I only need one.  I don't know if it is a
    #common convention to use the '_' symbol as the name for the unused variable, but
    #I saw it in some guy's code in the past, and I started using it.
    #(2) I use "path.join" because on unix operating systems and windows operating systems
    #they use different conventions for paths like '\' vs '/'.  path.join works on all operating
    #systems for making paths.
    
    #Defines what extensions to look for within the file (you can add more to this)
    IMAGE_FILE_EXTENSIONS = ('.bmp', '.gif', '.jpg', '.jpeg', '.png', '.tif', '.tiff')
    
    #Changes to the directory in which this script is contained
    thisDir,_ = path.split(path.abspath(argv[0]))
    chdir(thisDir)
    
    #Lists all the files/folders in the directory
    fileList = listdir('.')
    for file in fileList:
       
        #Checks if the item is a file (opposed to being a folder)
        if path.isfile(file):
           
            #Fetches the files extension and checks if it is .docx
            _,fileExt = path.splitext(file)
            if fileExt == '.docx':
               
                #Creates directory for the images
                newDirectory = path.join(thisDir, file + "-Images")
                if not path.exists(newDirectory):
                    mkdir(newDirectory)
    
                currentFile = open(file,"r")
                for line in currentFile:
                    print line
    
                sleep(5)
               
               
               
                #Opens the file as if it is a zipfile
                #Then lists the contents
                try:
                    zipFileHandle = ZipFile(file)
                    nameList = zipFileHandle.namelist()
               
                    for archivedFile in nameList:
                        #Checks if the file extension is in the list defined above
                        #And if it is, it extracts the file
                        _,archiveExt = path.splitext(archivedFile)
                        if archiveExt in IMAGE_FILE_EXTENSIONS:
                            zipFileHandle.extract(archivedFile, newDirectory)
                except:
                    pass

  7. #7
    JavaN00bie is offline Member
    Join Date
    Jun 2011
    Posts
    21
    Rep Power
    0

    Default

    Nvm, got this to work with some help.

    All I did was change the

    Java Code:
    thisDir,_ = path.split(path.abspath(argv[0]))
    in the Python script to...

    Java Code:
    thisDir = getcwd()

Similar Threads

  1. Running a script until [quit]
    By überfuzz in forum Java Applets
    Replies: 1
    Last Post: 04-13-2011, 08:48 PM
  2. calling python file from java
    By cool in forum AWT / Swing
    Replies: 3
    Last Post: 11-11-2010, 03:50 AM
  3. Jython : python for java
    By cotarelo in forum New To Java
    Replies: 1
    Last Post: 03-25-2010, 08:53 AM
  4. Call java Methods from Python Script
    By hofsoc in forum New To Java
    Replies: 1
    Last Post: 02-18-2009, 04:47 PM
  5. Running a script within IE
    By Java Tip in forum SWT
    Replies: 0
    Last Post: 07-25-2008, 02:33 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •