2015-07-12 65 views
-1

我必须从maven项目运行一个python脚本。我使用main方法创建了一个临时类,以检查它是否按预期工作,使用了流程构建器,如果我指定了python脚本的绝对路径,然后使用RUN作为Java应用程序从eclipse运行java类,它将起作用。从maven运行一个外部python脚本

如果我改变它getClass()。getResourceAsStream(“/ scripts/script.py”),它会抛出一个异常,因为它找不到python脚本。

什么是放置python脚本的最佳场所,以及如何在Java类中访问它而不指定完整路径。由于我对maven很陌生,可能是由于用于执行Java程序的方法。

package discourse.apps.features; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

import org.json.simple.JSONObject; 
import org.json.simple.parser.JSONParser; 
import org.json.simple.parser.ParseException; 



public class Test { 

protected String scriptPath = "/Users/user1/project1/scripts/script.py"; 
protected String python3Path = "/Users/user1/.virtualenvs/python3/bin/python3"; 


public static void main(String[] args) throws IOException { 
    new Test().score(); 
} 

public JSONObject score() { 
     String text1="a"; 
     String text2="b"; 
     JSONObject rmap =null; 

     try 
     { 

     String line= null; 
     String writedir=System.getProperty("user.dir")+ "/Tmp"; 
     String pbCommand[] = { python3Path, scriptPath,"--stringa", text1, "--stringb",text2,"--writedir", writedir }; 
     ProcessBuilder pb = new ProcessBuilder(pbCommand); 
     Process p = pb.start(); 

      InputStream is = p.getInputStream(); 
      InputStreamReader isr = new InputStreamReader(is); 
      BufferedReader br = new BufferedReader(isr); 
      while ((line = br.readLine()) != null) { 
       JSONParser parser = new JSONParser(); 
       rmap= (JSONObject) parser.parse(line); 
      } 

     } catch (IOException | ParseException ioe) { 
      System.err.println("Error running script"); 
      ioe.printStackTrace(); 
      System.exit(0); 
     } 

     return rmap; 
    } 
} 

这里是从PB命令的输出 pbCommand [0]:/用户/用户1/.virtualenvs/python3/bin中/ python3

pbCommand [1]:显示完整的Python脚本

import os,sys 
from pyrouge import Rouge155 
import json 
from optparse import OptionParser 

def get_opts(): 
    parser = OptionParser() 
    parser.add_option("--stringa", dest="str_a",help="First string") 
    parser.add_option("--stringb", dest= "str_b",help="second string") 
    parser.add_option("--writedir", dest="write_dir", help="Tmp write directory for rouge") 

    (options, args) = parser.parse_args() 

    if options.str_a is None: 
     print("Error: requires string") 
     parser.print_help() 
     sys.exit(-1) 

    if options.str_b is None: 
     print("Error:requires string") 
     parser.print_help() 
     sys.exit(-1) 

    if options.write_dir is None: 
     print("Error:requires write directory for rouge") 
     parser.print_help() 
     sys.exit(-1)  

    return (options, args) 

def readTextFile(Filename): 
     f = open(Filename, "r", encoding='utf-8') 
     TextLines=f.readlines() 
     f.close() 
     return TextLines 

def writeTextFile(Filename,Lines): 
     f = open(Filename, "w",encoding='utf-8') 
     f.writelines(Lines) 
     f.close() 

def rougue(stringa, stringb, writedirRouge): 
    newrow={} 
    r = Rouge155() 
    count=0 
    dirname_sys= writedirRouge +"rougue/System/" 
    dirname_mod=writedirRouge +"rougue/Model/" 
    if not os.path.exists(dirname_sys): 
     os.makedirs(dirname_sys) 
    if not os.path.exists(dirname_mod): 
     os.makedirs(dirname_mod) 
    Filename=dirname_sys +"string_."+str(count)+".txt" 
    LinesA=list() 
    LinesA.append(stringa) 
    writeTextFile(Filename, LinesA) 
    LinesB=list() 
    LinesB.append(stringb) 
    Filename=dirname_mod+"string_.A."+str(count)+ ".txt" 
    writeTextFile(Filename, LinesB) 
    r.system_dir = dirname_sys 
    r.model_dir = dirname_mod 
    r.system_filename_pattern = 'string_.(\d+).txt' 
    r.model_filename_pattern = 'string_.[A-Z].#ID#.txt' 
    output = r.convert_and_evaluate() 
    output_dict = r.output_to_dict(output) 
    newrow["rouge_1_f_score"]=output_dict["rouge_1_f_score"] 
    newrow["rouge_2_f_score"]=output_dict["rouge_2_f_score"] 
    newrow["rouge_3_f_score"]=output_dict["rouge_3_f_score"] 
    newrow["rouge_4_f_score"]=output_dict["rouge_4_f_score"] 
    newrow["rouge_l_f_score"]=output_dict["rouge_l_f_score"] 
    newrow["rouge_s*_f_score"]=output_dict["rouge_s*_f_score"] 
    newrow["rouge_su*_f_score"]=output_dict["rouge_su*_f_score"] 
    newrow["rouge_w_1.2_f_score"]=output_dict["rouge_w_1.2_f_score"] 
    rouge_dict=json.dumps(newrow) 
    print (rouge_dict) 


def run(): 
    (options, args) = get_opts() 
    stringa=options.str_a 
    stringb=options.str_b 
    writedir=options.write_dir 
    rougue(stringa, stringb, writedir) 


if __name__ == '__main__': 
    run() 

pbCommand [2]: - stringa

pbCommand [3]:一个

pbCommand [4]: - stringb

pbCommand [5]:乙

pbCommand [6]: - writedir

pbCommand [7]:/用户/用户1/PROJECT1/TMP

回答

0

将脚本放在主/资源文件夹中,然后将其复制到目标文件夹。 然后确保你使用类似的com.google.common.io.Resources类,你可以用

<dependency> 
    <groupId>com.google.guava</groupId> 
    <artifactId>guava-io</artifactId> 
    <version>r03</version> 
</dependency> 

加那我有一个这样的类,它有助于资源文件转换为字符串:

import java.net.MalformedURLException; 
import java.net.URI; 
import java.net.URL; 

import com.google.common.base.Charsets; 
import com.google.common.io.Resources; 

public class FileUtil 
{ 

    public static String convertResourceToString(URL url) 
    { 
     try 
     { 
      return Resources.toString(url, Charsets.UTF_8); 
     } 
     catch (Exception e) 
     { 
      return null; 
     } 
    } 

    public static String convertResourceToString(String path) 
    { 
     return convertResourceToString(Resources.getResource(path)); 
    } 

    public static String convertResourceToString(URI url) 
    { 
     try 
     { 
      return convertResourceToString(url.toURL()); 
     } 
     catch (MalformedURLException e) 
     { 
      return null; 
     } 
    } 

} 

一些建议,如果你正在学习maven尝试使用它而不是IDE来运行和打包你的应用程序,那就是它应该做的。然后,一旦您确信应用程序将作为打包的jar工作,那么就使用IDE来运行它。

+0

其实这是一个很大的maven项目,我只是试图运行一个单独的类,它具有测试功能的主要功能。我将脚本添加到资源文件夹,如果我调试整个脚本更改为一个字符串,但进程生成器不认为这是一个可执行的Python脚本,它会抛出一个ecxeption – AMisra

+0

你可以打印出pbCommand []或什么是actaully在进程生成器中执行,我建议在pbCommand []中执行“\”“+ scriptPath +”\“”。你也应该尝试执行你的路径变量中的脚本,并尝试使用这个类来打印你的脚本来验证它是否在正确的位置。 – Snickers3192