Summary of problems encountered in java calling python program!!!

Keywords: Python Java Anaconda encoding


Problems encountered:

1, java calls python with no result and no error.

2, java calls python to output garbled code

3, java output string wrapping problem

In the recent learning process, java programs are needed to call python projects, all of which are win10 systems

  • python project is about deep learning. It is written in pycharm, using python 3.7, and the compiling environment is in anaconda
  • java project is a java Web project written by ssm framework, which is written by MyEclipse
  • The task to be completed is to submit a picture (javaweb) on the web page, pass the submitted picture path to the python project, which recognizes the words contained in the picture and returns them to the java project, and feeds back to the user on the page.

In this process, I really encountered a lot of problems, also troubled me for several days, also searched a lot of methods on the Internet, finally, in the process of my continuous attempts, I succeeded!!!

Let's start with the basic method:

java calls python method summary:

Reference blog: Calling Python in Java

I also downloaded and installed Jpython, but it didn't solve my problem. For my project, it's OK to call directly through Runtime. Although it's simple and crude, it's good to achieve the goal.

Here comes the point! Problems encountered:

1, java calls python with no result and no error.

python program executes completely ok independently, and java calls python program without any return value or error. This is the problem that bothers me the most.

Part code:


from ocr import ocr
import numpy as np
from PIL import Image
from glob import glob
import sys

def single_pic_proc(image_file):
    image = np.array('RGB'))
    result, image_framed = ocr(image)
    return result,image_framed

if __name__ == '__main__':
     # Route
    image_files = glob(sys.argv[1])

    for image_file in sorted(image_files):
        # Result
        result, image_framed = single_pic_proc(image_file)
        for key in result:


package com.fh.controller.test;

public class test {
	 public static void main(String[] args) { 
	        try {	         
	           String url="D:\\1.jpg";
	           String[] args1 = new String[] { "D:\\softwear\\anaconda\\python.exe", "D:\\ocr2\\", url}; 
	           Process pr=Runtime.getRuntime().exec(args1);
               BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
	           String line;
	           while ((line = in.readLine()) != null) {
	          } catch (IOException e) {
	  		} catch (InterruptedException e) {
	    private static String getPara(String string) {
	        // TODO Auto-generated method stub
	        return null;

Be careful:

1. It's better not to write "Python" as the path of Python. In this way, the computer default Python will be used, and it should be written as the python directory used by the project. Because my computer has several pythons installed, I am running Python under anaconda, "D: \ \ software \ \ Anaconda \ \ Python" or "D: \ \ software \ \ Anaconda \ \ python. Exe".

2. All local packages imported in the project use absolute path.

The third-party package uses the python used by the project. If there is no problem with the python project running, then there is no problem with the third-party package import.

(from the network: running in CMD, the default path is the default path in python, so your file cannot be found, and the default path running on other ides is the path of the file, so it can take effect normally.)

Because this project of python is learning and not very familiar, I went to the command line to check the error reporting and changed the relative path of all projects to the absolute path (eclipse does not report an error, only so)

Console ran successfully:

Then run it in eclipse. As a result, new problems appear and the code is garbled.

2, java calls python to output garbled code

Two solutions:

1. Modify the python part and add it to the beginning of the file

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

2. Modify the java part and add the encoding format "GBK"

  BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream(),"GBK"));

Both methods can be used, but the first method in my project will affect the output when running python alone, resulting in garbled code. So I use the second method, which is simpler.

3, java output string wrapping problem

Add "\ n" at the end of the string and store it in the database. When the page is displayed as it is, there will be no line break. The simplest way is to add it at the end

"\ r\n", so that string fetching will wrap as required during page presentation.

     while ((line = in.readLine()) != null) {


Finally, on the project:


Maybe that's it. I'm also in the entry stage, but I have some opinions. If not, please give me more advice!

68 original articles published, 28 praised, 30000 visitors+
Private letter follow

Posted by jck on Fri, 13 Mar 2020 05:22:04 -0700