如何使用python执行java程序同时考虑输入和输出

2022-01-18 00:00:00 python subprocess java

将我的 python 程序视为 input.py

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文件是Hi.java

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);
       }
}

当我调用 input.execute_java(Hi.hava) 时,输出是 "Enter the string",当我输入字符串时说 "Jon",然后它再次将输出打印为输入字符串This is Jon",即它提供了两次完整的输出.可能是由于 python 代码 input=subprocess.Popen(cmd,stdin=PIPE) 导致的一个输出和由于代码 print proc.stdout.read() 而导致的第二个输出我希望它只打印一次.我该怎么办?我希望我的 python 变量接收 java 程序的所有输出,并使用该变量将输出显示在屏幕上.此外,如果有 java 程序的输入,我希望该用户输入将存储在我的 python 变量中的输入,并使用这个变量,我想将输入传递给 java 程序.我该怎么办?

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?

推荐答案

你应该使用 communicate 而不是 stdout.read.communicate 的参数是子进程的输入.此外,当您实际上不希望 shell 执行您的命令时,传递 shell=True 也是一个坏主意.相反,将参数作为列表传递:

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')

相关文章