说明
java调用Python2,并向Python2传参数(注意,python3不用看本文 !)
因为需要动态传参数,可能有中文乱码,也可能有些参数是空值
所以思考良久后,决定编码两次,和解码两次,来解决这个问题。在java用base64对参数转码,这里转码了两次,Python也解码了两次。
java端编码两次
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import net.sf.json.JSONObject;
public class Demo {
public static void main(String[] args) throws Exception {
String[] cmdarray = null;
String[] envp = null;
Map<String,String> map =new HashMap<String, String>();
map.put("name", "名字");
map.put("number", "123456");
JSONObject json =new JSONObject();
json.put("name",
Base64.encodeBase64String(map.get("name").getBytes("utf-8")));
json.put("number",
Base64.encodeBase64String(map.get("number").getBytes("utf-8")));
String jsonStr = json.toString();
jsonStr = Base64.encodeBase64String(jsonStr.getBytes("utf-8"));
if(isWindows()) {
cmdarray = new String[] { "cmd", "/c", "python D:\\python2\\test.py",jsonStr};
envp = new String[] {"path=D:\\Anaconda\\envs\\leantwo"};
}else {
cmdarray = new String[] { "/bin/sh","-c", "python D:\\python2\\test.py"};
envp = new String[] {"export PATH=$PATH:/usr/local/bin/python"};
}
try {
Process process = Runtime.getRuntime().exec(cmdarray, envp);
BufferedReader in = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
StringBuffer buffer = new StringBuffer();
while ((line = in.readLine()) != null) {
System.out.println(line);
buffer.append(line);
}
in.close();
int re = process.waitFor();
System.out.println(re);
System.out.println(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean isWindows() {
return System.getProperties().getProperty("os.name")
.toUpperCase().indexOf("WINDOWS") != -1;
}
python端解码两次
#for i in range(1, len(sys.argv)):
# print "参数", i, sys.argv[i]
jsonObject = json.loads(base64.b64decode(sys.argv[1]))
name = base64.b64decode(jsonObject['name'])
number = base64.b64decode(jsonObject['number'])