在Java中使用Python脚本(Eclipse)

Thi*_*mer 6 python java eclipse interpreter jython

我一直在寻找将我为朋友制作的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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

关于Python脚本的Java错误:

回溯(最近一次调用最后一次):
文件"C:/ Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Image-Extractor2.py",第19行,在thisDir中,_ = path.split(路径. abspath(argv [0]))IndexError:索引超出范围:0回溯(最近一次调用最后一次):
文件"C:/ Documents and Settings/user/workspace/Intern Project/Proposals/Converted Proposals/Image-Extractor2.py ",第19行,在thisDir中,_ = path.split(path.abspath(argv [0]))IndexError:index超出范围:0


蟒蛇:

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
Run Code Online (Sandbox Code Playgroud)

Voo*_*Voo 2

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

os.getcwd()

Return a string representing the current working directory.
Run Code Online (Sandbox Code Playgroud)

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

未经测试,但我认为 os.path.dirname(os.path.realpath( __ file__)) 应该可以工作(注意:删除那里的空格;我应该花时间详细查看格式化选项~)

  • 哇,效果太棒了!非常感谢,这个地方似乎比我研究过的所有其他论坛更有帮助。救星。 (2认同)