java执行python乱码问题

2023-12-14 15:51:26

Runtime.getRuntime().exec 乱码

用Runtime.getRuntime.exec()调用Python脚本时,Java端捕获脚本有中文输出时,输出的中文可能会是乱码,因为Python安装在Windows环境下的默认编码格式是GBK。

解决方法:

方法一

在被调用的脚本的开头增加如下代码,一定要添加到其他依赖模块import之前:

import io
import sys
 
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

?方法二:

	public static final String FILE_NAME = "now_func.py";
	
	public static String runPyScript(String day) {
		StringBuffer sb = new StringBuffer();
        Process proc = null;
        try {
        	String pythonFilePath = System.getProperty("python.filePath");
        	if(null== pythonFilePath) {
        		
        	}
        	String path = pythonFilePath+ File.separatorChar + FILE_NAME;
            String[] args1 = new String[] { "python", path, String.valueOf(day) };
            proc = Runtime.getRuntime().exec(args1);// 执行py文件
            //用输入输出流来截取结果
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "GB2312"));
            String line = null;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
        	if(null != proc) {
            	proc.destroy();
        	}
		}
		return sb.toString(); 
	}

jython-standalone 乱码

?jython-standalone 借助PyString?

	@Test
	public void runDemo() {
		// 调用python的解释器
		PythonInterpreter interpreter = new PythonInterpreter();
		// 执行Python语句
		String codeStr = "str = 'hello world!  中国 '; ";
		PyString code = Py.newStringUTF8(codeStr);
		interpreter.exec(code);
		interpreter.exec("print(str);");
	}

借助json

import json

def get_day(day):
    str = "今天是: "+ day;
    return json.dumps(str);
		String paramStr = "2023-12-11";
		PyString param = Py.newStringUTF8(paramStr);
		
		
		String path = "D:\\python\\now_func_no_main.py";
		PythonInterpreter interpreter = new PythonInterpreter();
		interpreter.execfile(path);
		PyFunction func = interpreter.get("get_day", PyFunction.class);
		PyObject pyobj = func.__call__(param);
		System.out.println(pyobj.toString());
        Object obj = JSON.parse(pyobj.toString());
        System.out.println(obj.toString());

?

文章来源:https://blog.csdn.net/kaige8312/article/details/134924891
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。