【发布时间】:2019-01-13 21:20:12
【问题描述】:
我正在使用 Jython 将字符串值传递给 python 脚本。在我的程序中,我多次这样做。但是,在测试期间,我正在运行以查看发送参数的类是否正常工作,我看到 python 脚本输出与初始输入相同的字符串值。
这是 Java 类:
public class SendToCal
{
PythonInterpreter interp = null;
StringWriter clout = null;
String [] arguments = null;
private String start=null,end=null,subject = null;
Properties props = new Properties();
public SendToCal(String start,String end, String subject)
{
try{
setInputs(start,end,subject);
arguments = getInputs(start,end,subject);
//---------------------------------------------
//---------------trying out jython test--------
props.setProperty("python.path","C:\\folder\\where\\I\\have\\stuff\\2.7-b1\\Lib', '__classpath__', '__pyclasspath__/");
PythonInterpreter.initialize(System.getProperties(), props,arguments);
this.interp = new PythonInterpreter();
clout = new StringWriter();
interp.setOut(clout);
interp.execfile("C:\\folder\\to\\file\\pyscript.py");
String outputStr = clout.toString();
System.out.println(outputStr);
clout.close();
}catch(IOException ex)
{
ex.printStackTrace();
}
}
public void setInputs(String start, String end, String sub)
{
this.start = start;
this.end = end;
this.subject = sub;
}
public String[] getInputs(String start, String end, String sub)
{
String [] arr = {this.start,this.end,this.subject};
return arr;
}
public static void main(String[] args) throws InterruptedException
{
String st2 = 2018+"-"+ 8 +"-"+ 6+ " " +"12:00";
String en2 = 2018+"-"+ 8 +"-"+ 6+ " " +"11:59";
String su2 = "YAY PYTHON AGAIN!!";
new SendToCal(st2, en2, su2);
TimeUnit.SECONDS.sleep(1);
String st = 1999+"-"+ 7 +"-"+ 17+ " " +"12:00";
String en = 1999+"-"+ 7 +"-"+ 17+ " " +"11:59";
String su = "YAY PYTHON!!";
new SendToCal(st, en, su);
}
}
另外,下面是我的python脚本:
import sys
def pyscript(arg1,arg2,arg3):
print ("calling python function with parameters:")
print arg1
print arg2
print arg3
pyscript(sys.argv[0],sys.argv[1],sys.argv[2])
我的问题是,当我使用两个或多个完全不同的字符串数组调用 Java 构造函数时,python 的输出是第一个数组输入的副本。任何帮助表示赞赏。
我得到以下输出:
calling python function with parameters:
2018-8-6 12:00
2018-8-6 11:59
YAY PYTHON AGAIN!!
calling python function with parameters:
2018-8-6 12:00
2018-8-6 11:59
YAY PYTHON AGAIN!!
我希望:
calling python function with parameters:
2018-8-6 12:00
2018-8-6 11:59
YAY PYTHON AGAIN!!
calling python function with parameters:
1999-7-17 12:00
1999-7-17 11:59
YAY PYTHON AGAIN!!
【问题讨论】:
-
代码不完整。没有 import 语句,“Here is the Java class:”之后的不是完整的类;这只是
SendToCal方法。请确保通过提供minimal reproducible example 可以重现问题。 -
我已经更新它以显示整个班级。谢谢!
-
请向我们展示您获得的确切输出和您期望的输出。我不明白“python 的输出是第一个数组输入的副本”。
-
好吧,我希望这些编辑更清楚。让我知道这是否有意义
-
或许这与
PythonInterpreter.initialize()有关?根据文档,这个方法应该只被调用一次。 jython.org/javadoc/org/python/util/…