在Java(Eclipse)中使用Python脚本

在Java(Eclipse)中使用Python脚本,java,python,eclipse,jython,interpreter,Java,Python,Eclipse,Jython,Interpreter,我一直在寻找将一位朋友为我制作的Python脚本合并到我正在尝试开发的Java应用程序中。经过一番尝试和错误,我终于发现了关于“Jython”的内容,并使用PythonInterpreter尝试运行脚本 但是,在尝试运行它时,Python脚本中出现了一个错误。这很奇怪,因为当我尝试在Java之外运行脚本时(在本例中为Eclipse IDE),该脚本工作正常,并且完全按照我的需要执行(从存储在同一目录中的.docx文件中提取所有图像) 有人能帮我吗 Java: import org.python.

我一直在寻找将一位朋友为我制作的Python脚本合并到我正在尝试开发的Java应用程序中。经过一番尝试和错误,我终于发现了关于“Jython”的内容,并使用PythonInterpreter尝试运行脚本

但是,在尝试运行它时,Python脚本中出现了一个错误。这很奇怪,因为当我尝试在Java之外运行脚本时(在本例中为Eclipse IDE),该脚本工作正常,并且完全按照我的需要执行(从存储在同一目录中的.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();
        }
    }
}
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 = getcwd()
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

关于Python脚本的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();
        }
    }
}
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 = getcwd()
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
回溯(最近一次呼叫最后一次):
文件“C:/Documents和 设置/用户/工作区/实习生 项目/建议/转换 提案/图像提取器2.py“,行 19,在 thisDir,z=path.split(path.abspath(argv[0])) 索引器:索引超出范围:0 回溯(最近一次呼叫最后一次):
文件“C:/Documents和 设置/用户/工作区/实习生 项目/建议/转换 提案/图像提取器2.py“,行 19,在 thisDir,z=path.split(path.abspath(argv[0])) 索引器:索引超出范围:0


Python:

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

我的猜测是,如果调用解释器,您不会得到命令行参数(这并不奇怪,它应该从哪里获得正确的值?[或者正确的值是什么?])

os.getcwd()

将返回工作目录,但可能这不是您想要的


未测试,但我认为os.path.dirname(os.path.realpath(_uuu文件_uuu))应该可以正常工作(注意:删除那里的空格;我应该在某个时候详细查看格式化选项~)

哇,工作得很好!非常感谢,伙计,这个地方似乎比我调查过的所有其他论坛都更有帮助。编辑:这正是我想要的,因为所有的文件都会存储在工作目录中并从那里访问。好吧,这真是太奇怪了。在我做了必要的改变之后,昨天一切都很顺利。现在我觉得我又回到了原点,因为它仍然不工作,我没有收到任何错误。@Joe好吧,如果没有错误,这意味着您使用的两个解决方案中的任何一个都指定了“错误”目录。我会先打印你使用的任何方法的结果,看看它会返回什么。