How to execute java program using python consideri

2019-01-18 16:35发布

Consider my python program as input.py

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):
java_class,ext = os.path.splitext(java_file)
cmd = ['java', java_class]
proc = subprocess.Popen(cmd,stdout=PIPE,stderr=STDOUT)
input=subprocess.Popen(cmd,stdin=PIPE)
print proc.stdout.read()

Java file I am using is Hi.java

import java.util.*;
class Hi
{
       public static void main(String args[])
       {
            Scanner t=new Scanner(System.in);
            System.out.println("Enter any string");
            String str=t.nextLine();
            System.out.println("This is "+str);
            int a=5;
            System.out.println(a);
       }
}

When I call input.execute_java(Hi.hava), the output is "Enter the string" and when I enter the string say "Jon", then again it prints the output as "Enter the string This is Jon" i.e. it is providing the entire output two times. Maybe one output due to the python code input=subprocess.Popen(cmd,stdin=PIPE) and second output due to the code print proc.stdout.read() I want it to get printed only once. What should I do? I want my python variable to receive all the output of java program and using that variable I will display the output on the screen. Also if there is an input to java program, I want that user to enter the input which will be stored in my python variable and using this variable, I want to pass the input to java program. What should I do?

1条回答
迷人小祖宗
2楼-- · 2019-01-18 17:15

You should use communicate instead of stdout.read. The argument of communicate is the input to the subprocess. Also, it's a bad idea to pass shell=True when you don't actually want a shell to execute your command. Instead, pass the arguments as a list:

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]
    proc = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    stdout,stderr = proc.communicate(stdin)
    print ('This was "' + stdout + '"')

compile_java('Hi.java')
execute_java('Hi.java', 'Jon')
查看更多
登录 后发表回答