这是一个心酸的历程。
py文件如下:
这里调用出现的问题主要是第三方包的问题,因为你的py文件里可能含有很多三方库文件,jython的jar包里可能不含有这个,所以这时需要你找到你已有三方库文件的exe,怎么找呢,去你的pycharm里找,不然java会调用计算机默认的python去做,而你可能只是把三方库文件下载到了某一个程序里,如果我这么说你不懂那就去pycharm里找:
java源码:
import org.python.core.Py; import org.python.core.PySystemState; import org.python.util.PythonInterpreter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class py { public static void main(String[] args) throws IOException { try{ System.out.println("start"); Process pr = Runtime.getRuntime().exec("C:\Users\神奇的刘dd\PycharmProjects\untitled\venv\Scripts\python.exe C:\Users\神奇的刘dd\PycharmProjects\untitled\毕设\TestMysql.py"); System.out.println("123"); BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); pr.waitFor(); System.out.println("end"); } catch (Exception e){ e.printStackTrace(); } } }
插入数据库也可以。亲测成功!
接受的python程序的返回值是乱码怎么办?
import org.python.core.Py; import org.python.core.PySystemState; import org.python.util.PythonInterpreter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class py { public static void main(String[] args) throws IOException { try{ System.out.println("start"); Process pr = Runtime.getRuntime().exec("C:\Users\神奇的刘dd\PycharmProjects\untitled\venv\Scripts\python.exe C:\Users\神奇的刘dd\PycharmProjects\untitled\毕设\QQNews.py"); System.out.println("123"); BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream(),"GBK")); String line; while ((line = in.readLine()) != null) { //String res=new String(line.getBytes("iso8859-1"), "utf-8"); System.out.println(line); } in.close(); pr.waitFor(); System.out.println("end"); } catch (Exception e){ e.printStackTrace(); } } }
这样设置字符集为GBK即可。