• 解决java与python整合过程的问题-执行python问题报错


    1. import org.python.util.PythonInterpreter;
    2. import java.io.DataInputStream;
    3. import java.util.Properties;
    4. public class a {
    5. public static void main(String[] args) throws Exception{
    6. Properties props = new Properties();
    7. props.put("python.home", "D:\\jython2.7.2\\software\\Lib");
    8. props.put("python.console.encoding", "UTF-8");
    9. props.put("python.security.respectJavaAccessibility", "false");
    10. props.put("python.import.site", "false");
    11. Properties properties = System.getProperties();
    12. PythonInterpreter.initialize(properties, props, new String[0]);
    13. PythonInterpreter interpreter = new PythonInterpreter();
    14. interpreter.exec("print('hello')");
    15. //当python文件中使用了 import 并调用了第三方库 执行以下命令就会报错
    16. //interpreter.execfile("F:\\graduate\\pro\\src\\main\\java\\p1.py");
    17. fun();
    18. }
    19. //此方法解决了python文件含有import 进入第三方库的问题
    20. public static void fun() throws Exception{
    21. String exe = "python";
    22. String command = "F:\\graduate\\pro\\src\\main\\java\\p1.py";
    23. String[] cmdArr = new String[] {exe,command};
    24. Process process = Runtime.getRuntime().exec(cmdArr);
    25. DataInputStream dis = new DataInputStream(process.getInputStream());
    26. String str = "";
    27. while((str = dis.readLine()) != null)
    28. System.out.println(str);
    29. }
    30. }

  • 相关阅读:
    C语言编程规范
    C++算法:二叉树的序列化与反序列化
    【MATLAB教程案例19】优化类算法的应用,如何针对不同问题选择不同的优化类算法
    C++模板初阶
    我的保研故事
    KubeSphere 3.3.0 离线安装教程
    上手Python之函数进阶
    JVM之垃圾回收器
    【C++11】
    Maven Spring jar包启动报错 排查
  • 原文地址:https://blog.csdn.net/lishifu_/article/details/126772119