1 | package felix.io; |
2 | |
3 | import java.util.Arrays; |
4 | |
5 | import org.python.core.PyCode; |
6 | import org.python.core.PyInteger; |
7 | import org.python.core.PyObject; |
8 | import org.python.util.PythonInterpreter; |
9 | |
10 | /** |
11 | * Class for executing python code (using Jython). |
12 | * @author Ce Zhang |
13 | * |
14 | */ |
15 | public class PythonExecutor { |
16 | |
17 | /** |
18 | * pycode |
19 | */ |
20 | PyCode pycode; |
21 | |
22 | /** |
23 | * python interpreter |
24 | */ |
25 | PythonInterpreter interp; |
26 | |
27 | /** |
28 | * Prepares given script for execution. |
29 | * @param script |
30 | */ |
31 | public void prepare(String script){ |
32 | interp = new PythonInterpreter(); |
33 | pycode = interp.compile(script); |
34 | |
35 | interp.exec("def felixio_push(*columns):\n" + |
36 | "\tif(len(columns) == 0):\n"+ |
37 | "\t\t_felix_donotusemyname_outkey.append('')\n" + |
38 | "\telse:\n" + |
39 | "\t\t_felix_donotusemyname_outkey.append(columns[0].replace('\\\\','\\\\\\\\').replace('\\t','\\\\t').replace('\\n', '\\\\n').replace('\\r', '\\\\r'))\n" + |
40 | "\t_felix_donotusemyname_outvalue.append('\t'.join(i.__str__().replace('\\\\','\\\\\\\\').replace('\\t','\\\\t').replace('\\n', '\\\\n').replace('\\r', '\\\\r') for i in columns[1:]))\n"); |
41 | |
42 | interp.exec("def felixio_collect(k, v):\n" + |
43 | "\t_felix_donotusemyname_outkey.append(k)\n"+ |
44 | "\t_felix_donotusemyname_outvalue.append(v)"); |
45 | |
46 | } |
47 | |
48 | /** |
49 | * Returns given variable. |
50 | * @param variable |
51 | * @return |
52 | */ |
53 | public PyObject get(String variable){ |
54 | return interp.get(variable); |
55 | } |
56 | |
57 | /** |
58 | * Sets given variable. |
59 | * @param name |
60 | * @param value |
61 | */ |
62 | public void set(String name, PyObject value){ |
63 | interp.set(name, value); |
64 | } |
65 | |
66 | /** |
67 | * Execuates given script. |
68 | * @param script |
69 | */ |
70 | public void execSingle(String script){ |
71 | interp.exec(script); |
72 | } |
73 | |
74 | /** |
75 | * The constructor. |
76 | */ |
77 | public PythonExecutor(){ |
78 | } |
79 | |
80 | /** |
81 | * The constructor with script. |
82 | * @param script |
83 | */ |
84 | public PythonExecutor(String script){ |
85 | this.prepare(script); |
86 | } |
87 | |
88 | /** |
89 | * Excecutes python script. |
90 | */ |
91 | public void run(){ |
92 | |
93 | interp.exec(pycode); |
94 | |
95 | } |
96 | |
97 | /** |
98 | * Main test method. |
99 | * @param args |
100 | * @throws Exception |
101 | */ |
102 | /* |
103 | public static void main(String[] args) throws Exception{ |
104 | |
105 | PythonExecutor pe = new PythonExecutor(); |
106 | pe.prepare("print sys"); |
107 | |
108 | pe.execSingle("import sys"); |
109 | |
110 | for(int i=0;i<10000;i++){ |
111 | pe.run(); |
112 | } |
113 | } |
114 | */ |
115 | |
116 | } |