run Java program with jar from Python

2020-07-27 02:47发布

I am trying to run a java file with a jar from Python. I first run the command :

java -classpath ".:/Users/blablalba/jackson-all-1.9.0.jar" parseJason

it worked perfectly. Then I wrote a small python script to execute the java file. (Updated: I made a change based on the suggestion below.

import os.path,subprocess
from subprocess import STDOUT,PIPE

def compile_java(java_file):
    subprocess.check_call(['javac', java_file])

def execute_java(java_file, stdin):
    java_class,ext = os.path.splitext(java_file)
   // cmd = ['java', java_class] change to
    cmd = ['java', 
  '-classpath',  '.:/Users/blablalba/jackson-all-1.9.0.jar', 
  'parseJason']
        proc = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
        stdout,stderr = proc.communicate(stdin)

compile_java('parseJason.java')
execute_java('parseJason.java', 'data.json','output_010.csv')

Data.json is the input file name and output_010.csv is the output file name. My java file gets those two parameters through reading the scanner.system.in.

Then I run the command :

    python parseJson.py

I received the following error:

import org.codehaus.jackson.map.ObjectMapper;
                                ^
parseJason.java:380: error: cannot find symbol
        ObjectMapper mapper = new ObjectMapper();
        ^
  symbol:   class ObjectMapper
  location: class parseJason
parseJason.java:380: error: cannot find symbol
        ObjectMapper mapper = new ObjectMapper();
                                  ^
  symbol:   class ObjectMapper
  location: class parseJason
3 errors
Traceback (most recent call last):
  File "parseJson.py", line 15, in <module>
    compile_java('parseJason.java')
  File "parseJson.py", line 5, in compile_java
    subprocess.check_call(['javac', java_file])
  File "/Users/***/anaconda2/lib/python2.7/subprocess.py", line 541, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['javac', 'parseJason.java']' returned non-zero exit status 1

Anyone has ideas what I am missing here? Thanks!

1条回答
戒情不戒烟
2楼-- · 2020-07-27 03:16
Command '['java', 'parseJason.java']'

The command should be the same as before

  • the classpath is missing
  • the main class is called parseJason, not parseJason.java

Try

cmd = ['java', 
  '-classpath',  '.:/Users/blablalba/jackson-all-1.9.0.jar', 
  'parseJason']
查看更多
登录 后发表回答