【问题标题】:Using a Python Script in Java (Eclipse)在 Java (Eclipse) 中使用 Python 脚本
【发布时间】:2011-09-20 14:37:56
【问题描述】:

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

有关 Python 脚本的 Java 错误:

回溯(最近一次通话最后一次):
文件“C:/文件和 设置/用户/工作区/实习生 项目/建议/转换 提案/Image-Extractor2.py",行 19,在 thisDir,_ = path.split(path.abspath(argv[0])) IndexError:索引超出范围:0 回溯(最近一次通话最后一次):
文件“C:/文件和 设置/用户/工作区/实习生 项目/建议/转换 提案/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

【问题讨论】:

    标签: java python eclipse jython interpreter


    【解决方案1】:

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

    os.getcwd()

    Return a string representing the current working directory.
    

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

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

    【讨论】:

    • 哇,效果很好!非常感谢,这个地方似乎比我看过的所有其他论坛更有帮助。救生员。
    • 编辑:这实际上是我想要的,因为所有文件都将存储在工作目录中并从那里访问。
    • 好吧,这太奇怪了。在我进行必要的更改后,昨天一切正常。现在我觉得我又回到了原点,因为它仍然无法正常工作,而且我没有收到任何错误。
    • @Joe 好吧,如果没有错误,这意味着您使用的两个解决方案中的任何一个都指定了“错误”目录。我会先打印你使用的任何方法的结果,看看它返回什么。
    猜你喜欢
    • 2012-08-31
    • 2014-07-02
    • 2022-10-18
    • 2017-10-12
    • 2011-07-17
    • 2014-06-09
    • 2011-01-25
    • 1970-01-01
    • 2013-08-11
    相关资源
    最近更新 更多