我想使用"PythonInterpreter"从Java调用python模块中的函数,这是我的Java代码
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");
PyObject someFunc = interpreter.get("helloworld.getName");
PyObject result = someFunc.__call__();
String realResult = (String) result.__tojava__(String.class);
System.out.println(realResult);
Run Code Online (Sandbox Code Playgroud)
和Python代码(helloworld.py)如下:
from faker import Factory
fake = Factory.create()
def getName():
name = fake.name()
return name
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是当我返回一个null PyObject时我正在调用interpreter.get.
知道出了什么问题吗?从IDLE可以很好地运行python代码
我刚刚对代码进行了一些更改,如下所示
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");
PyInstance wrapper = (PyInstance)interpreter.eval("helloworld" + "(" + ")");
PyObject result = wrapper.invoke("getName()");
String realResult = (String) result.__tojava__(String.class);
System.out.println(realResult);
Run Code Online (Sandbox Code Playgroud)
我在我的python模块中引入了一个类
from faker import Factory
class helloworld:
def init(self):
fake = …Run Code Online (Sandbox Code Playgroud) 我java.lang.IllegalStateException: Already connected在尝试运行以执行HTTPS GET请求时遇到异常HttpsURLConnection API.
请在下面找到代码:
HttpsURLConnection con = null;
try {
URL obj = new URL(url);
con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", header);
con.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");
String urlParameters = "schema=1.0&form=json&byBillingAccountId={EQUALS,cesar@abc.org}";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code = " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close(); …Run Code Online (Sandbox Code Playgroud)