Проблема запуска Python Script на Java (Eclipse) - PullRequest
3 голосов
/ 23 июня 2011

поэтому вчера я задал вопрос и подумал, что получил ответ, потому что все, казалось, работало нормально. Сегодня я возвращаюсь, чтобы попытаться запустить мою программу, и обнаружил, что ничего не происходит, и на этот раз я вообще не получаю никаких ошибок.

Чтобы дать вам представление о вещах, я хотел включить Python Script, созданный для меня другом, в приложение Java, которое я пытаюсь разработать. После некоторых проб и ошибок я наконец узнал о Jython и использовал PythonInterpreter, чтобы попытаться запустить скрипт.

Однако, пытаясь запустить его, я получил ошибку в скрипте Python. Это было решено предложением члена SO, предоставленного, чтобы изменить thisDir = getcwd (), или так я думал. Теперь я понятия не имею, что может быть не так, скрипт работает нормально и делает именно то, что мне нужно (извлечь все изображения из файлов .docx, хранящихся в том же каталоге), когда я запускаю его прямо из командной строки, поэтому я не знаю Есть идеи?

Может кто-нибудь помочь мне здесь?

Java

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();
        }
    }
}

Python:

from os import path, chdir, listdir, mkdir, gcwd
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 = gcwd()
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

EDIT

Просто добился некоторого прогресса, поэтому в Eclipse, когда я запускаю скрипт самостоятельно (без вызова через java) как «запуск Python», все работает отлично. Однако, когда я выполняю «Jython Run», сценарий spazzes, и он создает новые каталоги для изображений, однако он не будет извлекать сами изображения.

ОКОНЧАТЕЛЬНОЕ РЕДАКТИРОВАНИЕ

Чувак, просто винт дерьмовый Jython. Я только что установил Python на моем пути ...

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("C:\\Python27\\python.exe  \"C:\\Documents and Settings\\user\\workspace\\Intern Project\\Proposals\\Converted Proposals\\ImageExtractor2.py\"");

Бэм, отлично сработало.

Надеюсь, это поможет кому-то там.

...