在Java中使用Python脚本(Eclipse)

时间:2011-06-22 17:37:47

标签: java python eclipse jython interpreter

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

但是,在尝试运行它时,我在Python脚本中收到错误。这很奇怪,因为当我尝试在Java之外运行脚本(在这种情况下是Eclipse IDE)时,脚本工作正常并完全符合我的需要(从存储在同一目录中的.docx文件中提取所有图像)。

有人可以帮助我吗?

爪哇:

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脚本的Java错误:

  

追踪(最近的呼叫最后):
  文件“C:/ Documents and   设置/用户/工作区/实习生   项目/提案/转换   Proposals / Image-Extractor2.py“,行   19,在       thisDir,_ = path.split(path.abspath(argv [0]))   IndexError:索引超出范围:0   追溯(最近的呼叫最后):
  文件“C:/ Documents and   设置/用户/工作区/实习生   项目/提案/转换   Proposals / Image-Extractor2.py“,行   19,在       thisDir,_ = path.split(path.abspath(argv [0]))   IndexError:索引超出范围:0


的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 = 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

1 个答案:

答案 0 :(得分:2)

我的猜测是,如果调用解释器,你就不会得到命令行参数(不是那么令人惊讶,它应该在哪里获得正确的值?[或者什么是正确的值?])。

  

os.getcwd()

Return a string representing the current working directory.

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

未经测试,但我认为os.path.dirname(os.path.realpath(__ file__))应该可以工作(注意:删除那里的空格;我应该详细看一下格式化选项〜)< / p>