我有这个问题使用沟通从python到Java
import subprocess
str = ["haha", "hehe"]
p = subprocess.Popen("java -jar "hi.jar", stdin = subprocess.PIPE, stdout = subprocess.PIPE)
#p.communicate(str)
我想将列表传达给我的子流程,并获得列表的输出
我的问题是Java将如何处理这种通信?作为清单?
我正在使用它来在Java中处理它。
Scanner in = new Scanner(System.in)
//Not sure what to put here if i am using
in.nextline()
我正在尝试将列表通过管道传递到Java引擎进行处理并将输出作为列表从Java管道传递回python
这里有一些选择:
str()
或repr()
将列表转换为字符串表示形式。然后解析Java中的字符串。我选择第三个选项JSON,因为这为可通信的数据结构类型提供了更大的灵活性。例如,您以后可能会发现自己想要传输Python字典。以后您可能还会发现想要Java应用程序发送回复,并且JSON也可以在这里使用。
Python将列表作为JSON字符串发送:
import json
import subprocess
# send a Python list...
p = subprocess.Popen("java -jar "hi.jar", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
o, e = p.communicate(json.dumps(["haha", "hehe"]))
>>> print o
handleInput(): got a JSONArray (list) containing 2 elements
haha
hehe
# send a Python dictionary...
p = subprocess.Popen("java -jar "hi.jar", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
o, e = p.communicate(json.dumps({"hee": "haw", "blah": "blah"}))
>>> print o
handleInput(): got a JSONObject (map) containing 2 items
hee: haw
blah: blah
并示例Java代码以接收和解析JSON。它可以处理基本列表和字典。这将使用json-simple
包进行解析:
import java.util.Scanner;
import java.util.Iterator;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
class JSONMessageHandler {
void handleInput(JSONArray list)
{
System.out.println(
"handleInput(): got a JSONArray (list) containing " +
list.size() + " elements");
for (Object o : list)
System.out.println(o);
}
void handleInput(JSONObject map)
{
System.out.println(
"handleInput(): got a JSONObject (map) containing " +
map.size() + " items");
for (Iterator it = map.keySet().iterator(); it.hasNext();)
{
Object key = it.next();
System.out.println(key + ": " + map.get(key));
}
}
}
class Hi {
public static void main(String[] args) throws ParseException {
Scanner in = new Scanner(System.in);
Object obj = new JSONParser().parse(in.nextLine());
JSONMessageHandler msgHandler = new JSONMessageHandler();
if (obj instanceof JSONArray)
msgHandler.handleInput((JSONArray)obj);
else if (obj instanceof JSONObject)
msgHandler.handleInput((JSONObject)obj);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句