python call java jar

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python call java jar相关的知识,希望对你有一定的参考价值。

python脚本如何调用Java的jar文件呢?

HelloWorld.java

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("hello world");
        String input = args[0];
        String output = input.toUpperCase();
        System.out.print(output);
    }

}

javacaller.py

# python3
# coding = utf-8

from subprocess import Popen, PIPE, STDOUT

mycmd = [java, -jar, HelloWorld.jar, logan]

pipe = Popen(mycmd, stdout=PIPE, stderr=STDOUT)

for line in pipe.stdout:
    print(line, type(line))
    if isinstance(line, bytes):
        line_decode = line.decode(utf-8)
        print(decode:, line_decode, type(line_decode))

print(done)

输出:

b‘hello world\n‘ <class ‘bytes‘>
decode: hello world
<class ‘str‘>
b‘LOGAN‘ <class ‘bytes‘>
decode: LOGAN <class ‘str‘>
done

注意点:

1. java的 System.out.println自带换行

2. java返回的结果需要decode

 

参考资料:

How to get the output from .jar execution in python codes? 






以上是关于python call java jar的主要内容,如果未能解决你的问题,请参考以下文章

[工作积累] UE4 并行渲染的同步 - Sync between FParallelCommandListSet & FRHICommandListImmediate calls(代码片段

Android代码片段

实用代码片段

Android开发常用代码片段

Python面向对象学习之八,装饰器

触发Java JAR以使用C ++运行并传递String